BigInteger循环相加
时间: 2024-06-11 19:08:21 浏览: 11
可以使用Java的BigInteger类来进行大整数的循环相加。以下是一个示例代码:
```java
import java.math.BigInteger;
public class BigIntegerLoopAddition {
public static void main(String[] args) {
BigInteger sum = BigInteger.ZERO;
for (int i = 1; i <= 100; i++) {
BigInteger num = BigInteger.valueOf(i);
sum = sum.add(num);
}
System.out.println("The sum of 1 to 100 is: " + sum);
}
}
```
在上面的代码中,我们使用BigInteger类来表示大整数。首先,我们使用BigInteger.ZERO初始化一个初始值为0的BigInteger对象sum。然后,我们使用循环从1到100依次遍历整数,并使用BigInteger.valueOf()将整数转换为一个BigInteger对象。最后,我们使用add()方法将每个BigInteger对象加到sum中。最终,我们打印出循环相加的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)