public static void main(String[] args) {
int maxNum, sum, counter; // input value
Scanner input = new Scanner(System.in);
System.out.print("How many odd numbers should I add up?: ");
maxNum = input.nextInt();
sum = 0;
for (counter = 1; counter < maxNum; counter++)
{
sum = counter + maxNum;
}
System.out.println("\n" + "The sum of the odd numbers between 1 and " + maxNum + " is: " + sum);
}
根据那个特定的代码,它应该只通过奇数来解决加法问题。
现在我尝试了一个数字 5,根据我的输出:
How many odd numbers should I add up?: 5
The sum of the odd numbers between 1 and 5 is: 9
它有效。但是当我尝试另一个数字 10 时,出了点问题:
How many odd numbers should I add up?: 10
The sum of the odd numbers between 1 and 10 is: 19
我知道我的数学题,但是从 1 到 10 的奇数加起来不是 19,它加起来是 25。
代码有问题。任何人都可以找出问题所在吗?
最佳答案
for (counter = 1; counter < maxNum; counter+=2)
{
sum += counter;
}
您添加了错误的号码。
关于java - 在循环中对奇数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514241/