C ++程序使用动态编程查找数字的阶乘
正整数n的阶乘等于1 * 2 * 3 * ... n。不存在负数的阶乘。这里给出了一个C ++程序,以便使用动态编程来找出给定输入的阶乘。
算法
Beginfact(int n):
Read the number n
Initialize
i = 1, result[1000] = {0}
result[0] = 1
for i = 1 to n
result[i] = I * result[i-1]
Print result
End
范例程式码
#include <iostream>using namespace std;
int result[1000] = {0};
int fact(int n) {
if (n >= 0) {
result[0] = 1;
for (int i = 1; i <= n; ++i) {
result[i] = i * result[i - 1];
}
return result[n];
}
}
int main() {
int n;
while (1) {
cout<<"Enter integer to compute factorial (enter 0 to exit): ";
cin>>n;
if (n == 0)
break;
cout<<fact(n)<<endl;
}
return 0;
}
输出结果
Enter integer to compute factorial (enter 0 to exit): 22
Enter integer to compute factorial (enter 0 to exit): 6
720
Enter integer to compute factorial (enter 0 to exit): 7
5040
Enter integer to compute factorial (enter 0 to exit): 10
3628800
Enter integer to compute factorial (enter 0 to exit): 0
以上是 C ++程序使用动态编程查找数字的阶乘 的全部内容, 来源链接: utcz.com/z/341039.html