程序以查找数字的阶乘并为负整数输入提供错误消息

Program to find the factorial of number and to give error message for negative integer input

本文关键字:输入 整数 消息 错误 查找 数字 阶乘 程序      更新时间:2023-10-16

我正在学习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/上阅读完整的代码说明