用Java实现一个1到100的叠加算法
时间: 2024-05-13 15:16:21 浏览: 19
您好,以下是用Java实现1到100的叠加算法的代码:
```java
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("1到100的叠加和为:" + sum);
}
}
```
在上面的代码中,我们使用了一个for循环来遍历1到100的所有数,并使用一个变量sum来记录它们的叠加和。最后输出sum的值即可得到结果。
相关问题
java代码实现 ImmutableList对象持续叠加另一个ImmutableList对象
可以使用Guava库中的ImmutableList类来实现ImmutableList对象持续叠加另一个ImmutableList对象的操作。以下是Java代码示例:
```java
import com.google.common.collect.ImmutableList;
public class ImmutableExample {
public static void main(String[] args) {
ImmutableList<String> list1 = ImmutableList.of("a", "b", "c");
ImmutableList<String> list2 = ImmutableList.of("d", "e", "f");
// 使用concat方法将两个ImmutableList对象叠加
ImmutableList<String> result = ImmutableList.<String>builder()
.addAll(list1)
.addAll(list2)
.build();
System.out.println(result); // 输出 [a, b, c, d, e, f]
}
}
```
在上述示例中,我们使用了`concat`方法将`list1`和`list2`叠加,生成了一个新的`ImmutableList`对象`result`。需要注意的是,由于`ImmutableList`对象本身是不可变的,因此每次叠加都会生成一个新的对象。
写一个1-100递归叠加的C语言代码
下面是一个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 n = 100;
int result = sum(n);
printf("1 + 2 + ... + %d = %d\n", n, result);
return 0;
}
```
在该代码中,sum() 函数使用递归的方式来计算 1-100 的累加和。当 n 等于 1 时,函数返回 1;否则,函数返回 n 和 sum(n-1) 的和。在 main() 函数中,我们调用 sum() 函数来计算 1-100 的累加和,并将结果输出到控制台上。
该代码的输出结果为:
```
1 + 2 + ... + 100 = 5050
```
这是因为 1-100 的累加和为 5050。