#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0) {
cout << "Error: negative integer." << endl;
return 1;
}
int result = factorial(n);
cout << n << "! = " << result << endl;
return 0;
}
在上面的代码中,我们定义了一个递归函数factorial,该函数接受一个非负整数n作为参数,计算n的阶乘并返回结果。当n等于0时,阶乘为1,因此函数返回1。否则,函数计算n的阶乘并返回n * factorial(n - 1)的结果。在main函数中,我们首先接受用户输入的非负整数n,并检查输入是否合法。如果输入的n为负数,则输出“Error: negative integer.”的错误信息并返回1退出程序。否则,我们调用递归函数factorial计算n的阶乘,并输出结果。最后,我们返回0退出程序。