用递归方法算S=1+2+3+…+n
时间: 2023-12-15 16:07:30 浏览: 136
用递归求1+2+3+...+n的程序
以下是两种语言的递归方法求解S=1+2+3+...+n的和:
- C++代码:
```cpp
#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;
return 0;
}
```
- Java代码:
```java
public class Sum {
public static int funSum(int n) {
if(n == 1) return 1;
else return n + funSum(n-1);
}
public static void main(String[] args) {
int n = 10;
int sum = funSum(n);
System.out.println("the sum is: " + sum);
}
}
```
阅读全文