用递归实现从1加到100
时间: 2024-03-06 10:50:37 浏览: 23
好的,那么以下是Java代码实现从1加到100的递归:
```java
public class Main {
public static void main(String[] args) {
int sum = add(1);
System.out.println("1+2+...+100=" + sum);
}
public static int add(int n) {
if (n == 100) {
return 100;
} else {
return n + add(n + 1);
}
}
}
```
在这个例子中,add()方法是递归的,它首先检查参数n是否等于100。如果是,那么它返回100,否则它返回n + add(n + 1)。这个add()方法在每个递归步骤中都会调用自身,直到n等于100,然后返回相应的值。在main()方法中,我们调用add()方法,并将结果打印到控制台上。
相关问题
C++用递归实现从1加到100
好的,以下是使用递归实现从1加到100的C代码:
```c
#include <stdio.h>
// 递归函数
int sum(int n)
{
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
int main()
{
int result = sum(100);
printf("1到100的和为:%d\n", result);
return 0;
}
```
这段代码利用了递归函数来实现从1加到100的累加操作。其中,sum函数中判断了递归的结束条件,当n为1时,直接返回1;否则,返回n与sum(n-1)的和。在主函数中调用sum函数,并将结果输出。
用c++ 实现 1加到100 递归
以下是使用C++递归实现1到100的累加:
```cpp
#include <iostream>
using namespace std;
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n-1);
}
}
int main() {
int result = sum(100);
cout << "The sum of 1 to 100 is: " << result << endl;
return 0;
}
```
在这个程序中,我们定义了一个名为sum的函数,它使用递归来计算从1到n的总和。如果n等于1,则返回1。否则,它将n加上从1到n-1的总和,以此类推,直到n等于1。
在主函数中,我们调用sum函数,并将100作为参数传递给它。最终,我们打印出1到100的总和。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)