我正在学习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 :(得分: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;
}
答案 1 :(得分: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/
上的完整代码说明