10.输入一个数,求这个数的阶乘
(1)运用循环:
#include<iostream> using namespace std; int JieCheng(int); int main() { int n; cout<<"please input an number: "<<endl; cin>>n; cout<<JieCheng(n); } int JieCheng(int n) { int m=1; for(int i=1;i<=n;i++) { m*=i; } return m; }
(2)运用递归:
#include<iostream> using namespace std; int JieCheng(int); int main() { int n; cout<<"please input an number: "<<endl; cin>>n; cout<<JieCheng(n); } int JieCheng(int n) { if(n==1) return 1; return n*JieCheng(n-1);//运用递归 }