程序以查找数字的阶乘并为负整数输入提供错误消息
Program to find the factorial of number and to give error message for negative integer input
我正在学习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;
}
我没有
检查您的阶乘函数是否返回正确的结果。此外,您可能希望将其递归,:)
为您的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;
}
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/上阅读完整的代码说明
相关文章:
- 如何打印不带空格的输入整数?
- 编写一个程序,输入整数 n 并打印该数字的字符数(符号除外)
- 如何在不中断剩余代码的情况下仅C++中输入整数
- 如何在输入整数时中断 for 循环
- C++ 在 CIN 双精度时挂起,但如果输入整数,则继续
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何输入整数并将其从最高到最低排序
- 如何创建一个程序,用户输入整数并输出90度数字金字塔
- 使用对输入整数的文件输入
- 使用户输入整数字符串,然后输出不同的字符串
- 从 fstream 到 2d 矢量的输入整数<矢量<int>> C++
- 用户输入整数后跟垃圾
- 输入整数直到 C/C++ 中的换行符
- 输入整数的最快方法
- C++循环 - 输入整数,直到用户退出
- 尝试输入整数行并在以矢量作为存储的函数的插入排序类型中排序
- 如何使C++程序在用户输入整数时抛出错误,而需要字符串
- 当要求输入整数并使用isdigit检查时,将char转换为int
- 如何通过指针输入整数数组并打印出数组和数组的大小(C++)
- 如果打印后输入整数,则C++分段故障,但其他情况下可以