输入一个数n,然后求从1到n的所有整数的阶乘的和。
例如:输入20;则,s=1!+2!+3!+4!+……+20!
分析:这个题目是进行了多个相似的运算,然后连续加和,可以使用循环结构来解决:
使用递归调用的方法:
#include<iostream>
using namespace std;
int main(){
int n,i=1;
cout<<"please input a positive integer:";
cin>>n;
long s=0;
long liancheng(int x);
while(i<=n){
s=liancheng(i)+s;
i++;
}
cout<<"the result is "<<s<<endl;
return 0;
}
long liancheng(int x){
if(x==1)return 1;
else return(x*liancheng(x-1));
}
当然,还有不使用递归调用的方法:
#include<iostream>
using namespace std;
int main(){
int n,i=1;
cout<<"please input a positive integer:";
cin>>n;
long s=0;
long liancheng(int x);
while(i<=n){
s=liancheng(i)+s;
i++;
}
cout<<"the result is "<<s<<endl;
return 0;
}
long liancheng(int x){
int j=1;
while(x>0){
j=j*x;
x--;
}
return j;
}