递归小函数

利用递归求1+2+3+4+……+N

#include<iostream>

using namespace std;

int sum(int n)
{
if(n == 0)
{
return 0;
}
return sum(n - 1)+n;//注意返回式子的书写
}

 

int main(void)//主函数为空不需要返回值
{
int n=0;
cin >> n;
cout<<sum(n)<<endl;

}

posted @ 2021-05-12 15:41  焓青  阅读(41)  评论(0)    收藏  举报