附上代码:
// Chapter6_2.cpp : Defines the entry point for the application.
// 用递归函数求 s=1+2+3+...+n 的和
#include "stdafx.h"
#include<iostream>
using namespace std;
int funSum(int n)
{
if(n == 1)
return 1;
else
return n+funSum(n-1);
}
int main()
{
int n,sum;
cout << "input n: ";
cin >> n;
sum = funSum(n);
cout << "the sum is: " << sum << endl;
system("pause");
return 0;
}
运行结果如下: