C++ 求n的阶乘n!(n>0)
一、方法1:用循环#include <iostream>using namespace std;int main(int argc, const char * argv[]) { int i, n, res; // res存储积 // 输入测试数据n while(cin >> n) { res = 1;
·
一、方法1:用循环
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int i, n, res; // res存储积
// 输入测试数据n
while(cin >> n) {
res = 1;
i = 1;
// 求n的阶乘
while(i <= n) {
res *= i;
i++;
}
cout << n << "的阶乘为:" << res << endl;
}
return 0;
}
二、方法2:用递归
#include <iostream>
using namespace std;
int toFactorial(int n) {
if(n == 1) // 终止状态
return 1;
else
return n * toFactorial(n - 1); // 归纳项
}
int main(int argc, const char * argv[]) {
int n;
while(cin >> n) {
cout << n << "的阶乘为:" << toFactorial(n) << endl;
}
return 0;
}
运行结果:
更多推荐
所有评论(0)