java似乎无法获得前面数字的正确总和
因此,我正在完成我的代码的一部分,希望它打印出用户输入之前的数字的总和,但我无法得到正确的总和。例如,如果用户输入“4”,那么总和应该是10,因为4+3+2+1=10,但当我输入4时,我得到5。有人能给我解释一下发生了什么事吗?我很确定这是在我的for循环中,因为这是唯一给我带来麻烦的部分,但我不确定。另外,代码的第一位就在那里,因为我们假设用户的输入限制在3到10之间,并在字后打印相应数量的符号。谢天谢地,我得到了这些部件,但就我所知,错误可能仍然存在。再次感谢任何愿意帮忙的人
int count2 = 0;
do {
System.out.print("Enter a number to use for Part B loops: ");
count2 = keybd.nextInt();
if (count2 > 10 || count2 < 3) {
System.out.print("Error: number must be between 3 and 10, inclusive.\n");
}
} while (count2 > 10 || count2 < 3);
int i = 1;
System.out.print("Spring");
while (i <= count2) {
System.out.print("/\\");
i++;
}
System.out.println("Break");
System.out.print("Sum of values 1 through " + count2 + " = ");
int sum = 0;
for (i = 1; i <= count2; i++);
{
sum += i;
}
System.out.print(sum);
# 1 楼答案
实际上问题是分号(;)在你的for循环之后。你的代码现在所做的是将i计数器从1循环到count2,然后用(i=count2+1)退出for循环,然后执行代码块{sum+=i},并使sum=count2+1
所以只要去掉分号就可以了