解法一:使用公共变量s,递归循环1~n加到s上
#include<bits/stdc++.h>
using namespace std;
int n,s;
void fun(int i){if(i<=n){s=s+i;fun(i+1);}}int main(){cin>>n;fun(1);cout<<s;return 0;
}
解法二:通过层层累加,然后将和层层返回,求和
#include<bits/stdc++.h>
using namespace std;
int n;
int fun(int i){if(i<=n){return i+fun(i+1);}else return 0;
}int main(){cin>>n;cout<<fun(1);return 0;
}
解法三:通过输入参数,层层累加求和
#include<bits/stdc++.h>
using namespace std;
int n;
int fun(int i,int s){if(i<=n){return fun(i+1,s+i);}else return s;
}int main(){cin>>n;cout<<fun(1,0);return 0;
}