序号:515
打印1到n累加的递归过程
Time Limit:1s Memory Limit:512MB
题目描述:
用递归的方法求1+2+3+……+N,输出递归过程,具体见输出样例
输入格式:
一个整数n,(1<n<20)
输出格式:
1到n的累加过程,具体见输出样例
输入样例:
5
输出样例:
sum(5)=sum(4)+5 sum(4)=sum(3)+4 sum(3)=sum(2)+3 sum(2)=sum(1)+2 sum(1)=1 sum(2)=3 sum(3)=6 sum(4)=10 sum(5)=15
#include<bits/stdc++.h>
using namespace std;
int n,res;
int sum(int x){
if(x==1){
cout<<"sum(1)=1\n";
return 1;
}
cout<<"sum("<<x<<")=sum("<<x-1<<")+"<<x<<"\n";
res=x+sum(x-1);
cout<<"sum("<<x<<")="<<res<<"\n";
return res;
}
int main(){
cin>>n;
sum(n);
}