2016-02-12 17 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/