
数字“n”的阶乘可以通过将“1”到“n”的数字相乘来计算。“0”的阶乘是“1”,负数不能求阶乘。它用符号“!”表示。
n! = 1 * 2 * 3 * 4 *……* n。
5! = 1*2 *3*4*5 = 120.
在这里,您将学习如何使用 C++ 中的 for 循环计算数字的阶乘。
提示用户输入一个数字。将该数字读入整型变量 n。声明一个长双精度变量 fact = 1。
for 循环 计算其他数字的阶乘。从 1 到 n 启动一个 for 循环,并在循环内部计算 fact *= i。注意:零的阶乘定义为一,即 0 ! = 1
步骤 1: 调用头文件 iostream.
步骤 2: 使用 namespace std。
步骤 3: 打开整型主函数; int main().
步骤 4:声明整型变量;n、fact
步骤 5:打印消息,提示输入一个正整数。
步骤 6:将用户输入读入变量 n。
步骤 7:如果 n < 0,则打印错误消息。否则转到步骤 8
步骤 8:对于 i = 1 到 n;fact *= i;打印 fact
步骤 9:打印 0! 的 fact = 1
步骤 10: 退出。
#include <iostream>
using namespace std;
int main() {
int n;
long double fact = 1.0;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
fact *= i;
}
cout << "Factorial of " << n << " = " << fact;
}
return 0;
}
Run 1 Enter a positive integer: 9 Factorial of 9 = 362880 Run 2 Enter a positive integer: -8 Error! Factorial of a negative number doesn't exist. Run 3 Enter a positive integer: 0 Factorial of 0 = 1