2016-02-12 77 views
0

我正在學習C++,並試圖創建一個程序來查找正整數的階乘。我已經能夠找到正整數的階乘。但是,當輸入不是正整數時,我仍然試圖讓程序給出錯誤消息。到目前爲止,錯誤消息已經與標準輸出消息結合在一起。程序找到數字的階乘,並給出負整數輸入的錯誤消息

我該如何構造循環,以便在正整數輸入中找到給定正整數的階乘,而在輸入不是正整數時僅提供錯誤消息?代碼如下。謝謝。

#include<iostream> 
#include<string> 

using namespace std; 

int main() 

{ 

    int i; 
    int n; 
    int factorial; 

    factorial = 1; 

    cout << "Enter a positive integer. This application will find its factorial." << '\n'; 
    cin >> i; 

    if (i < 1) 
    { 
     cout << "Please enter a positive integer" << endl; 
     break; 
    } 

    else 
     for (n = 1; n <= i; ++n) 
     { 
      factorial *= n; 
     } 

    cout << " Factorial " << i << " is " << factorial << endl; 

    return 0; 
} 
+0

完整的代碼解釋'打破;'將退出循環或開關的括號括起來的部分。作爲「if」中的最後一行,它什麼都不做。 – user4581301

+0

另外值得注意的是,在factorial溢出並給出錯誤結果之前,您只能處理高達12(32位'int')或20(64位'int')的階乘。您可能需要查看Big Integer庫來處理更大的因子。 – user4581301

回答

0

我沒有檢查您的因子函數是否返回正確的結果。此外,您不妨讓它遞歸,:)

添加括號爲您else

#include<iostream> 
#include<string> 

using namespace std; 

int main() 

{ 

    int i; 
    int n; 
    int factorial; 

    factorial = 1; 

    cout << "Enter a positive integer. This application will find its factorial." << '\n'; 
    cin >> i; 

    if (i < 1) 
    { 
     cout << "Please enter a positive integer" << endl; 
     break; 
    } 

    else { 
     for (n = 1; n <= i; ++n) 
     { 
      factorial *= n; 
     } 
     cout << " Factorial " << i << " is " << factorial << endl; 
    } 

    return 0; 
} 
+0

謝謝,@Tacocat – 0x1000001

+0

沒問題。謝謝! – Tacocat

0

還有的數量C++程序負責處理正數,負數和零也是一個完整的階乘。

#include<iostream> 
using namespace std; 
i 

nt main() 
{ 
    int number,factorial=1; 
    cout<<"Enter Number to find its Factorial: "; 
    cin>>number; 
    if(number<0) 
    { 
     cout<<"Not Defined."; 
    } 
    else if (number==0) 
    { 
     cout<<"The Facorial of 0 is 1."; 
    } 
    else 
    { 
     for(int i=1;i<=number;i++) 
     { 
      factorial=factorial*i; 
     } 
    cout<<"The Facorial of "<<number<<" is "<<factorial<<endl; 
    } 
    return 0; 
} 

你可以閱讀http://www.cppbeginner.com/numbers/how-to-find-factorial-of-number-in-cpp/