gpt4 book ai didi

java - java中对前N个数字求和

转载 作者:行者123 更新时间:2023-12-01 18:17:02 24 4
gpt4 key购买 nike

Hello, I am new to programming and I am trying to write a small program where it will calculate the sum for first N numbers. The problem is it does not work for even numbers. I have not managed to figure out why. My code is as follow:

int n = Integer.parseInt(args[0]);
int sum = (1+n)/2*n;
System.out.println(sum + " is the sum of first " + n + " numbers");

最佳答案

它甚至不适用于 n,因为 (n+1)/2 被截断为 int。

这意味着,例如,如果 n=4(n+1)/2 结果为 2 而不是 2.5,因此当您将其乘以 n 时,您得到 8,而不是所需的 10。

您只需更改操作顺序即可解决此问题。如果您首先将 n 乘以 (n+1),则结果保证是偶数,因此将其除以 2 将得出正确的答案。

int sum = n*(1+n)/2;

关于java - java中对前N个数字求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com