正整数n的阶乘等于1 * 2 * 3 * ... n。不存在负数的阶乘。这里给出了一个C ++程序,以便使用动态编程来找出给定输入的阶乘。
Begin fact(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): 2 2 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