//4.2分别使用循环和递归两种策略求二项式从c(n,k); //以for循环运行c(n,k) #include <iostream> using namespace std; int sum(int m); int main() { int n,k; int sum_n,sum_k,sum_i,sum_n_k; cout<<"请输入C(n,k)中的n值:"<<endl; cin>>n; cout<<"请输入C(n,k)中的k值:"<<endl; cin>>k; if(n<k) { cout<<"error,please input again."<<endl; return 0; } sum_n=sum(n); sum_k=sum(k); sum_i=sum(n-k); sum_n_k=sum_n/(sum_k*sum_i); cout<<"C(n,k)="<<sum_n_k<<endl; return 0; } int sum(int m) { int i,sum_m=1; for(i=1;i<=m;i++) sum_m*=i; return sum_m; } //以递归的方式算C(n,k) #include <iostream> using namespace std; int sum(int n,int k); int main() { int n,k; cout<<"请输入C(n,k)中的n值:"<<endl; cin>>n; cout<<"请输入C(n,k)中的k值:"<<endl; cin>>k; if(n<k) { cout<<"error,please input again."<<endl; return 0; } cout<<"C(n,k)="<<sum(n,k)<<endl; return 0; } int sum(int n,int k) { if(k>n/2) k=n-k; if(k==0||n==1) return 1; else return sum(n-1,k)+sum(n-1,k-1); }