英文:
In this code, error showing "division by zero", for the condition inside the while loop. Why is this happening?
问题
public static void main(String[] args) {
int num = 31;
int j = 1, c = 0;
while (num != 0) {
//System.out.println(j);
if (num % j == 0) {
c += j;
}
j++;
}
System.out.println(c);
}
英文:
> Here when I add System.out.println(j) inside the loop, the initial number is random, and the next outputs are huge values from 400000
>Value of j is Initialized to 1, does while loop counts all int values unless mentioned?
public static void main(String[] args) {
int num = 31;
int j = 1, c = 0;
while (num != 0) {
//System.out.println(j);
if (num % j == 0) {
c += j;
}
j++;
}
System.out.println(c);
}
答案1
得分: 1
在正常情况下,唯一能够退出循环的方式是当 num
变为 0
。但是你从未将 num
重新赋值为其他数字,所以它始终是 31
,因此循环不会正常结束。
然而,在你的循环中,每次经过时都会对 j
进行递增。j
被声明为整数类型。整数类型有定义的最大值,超过该值后会变为最小值,所以在达到最大(正)数值后,经过另一次增加,会得到最小(负)数值。然后继续递增直至达到 0
。此时,应用程序会尝试除以 0
,从而引发异常。
(参考链接:https://stackoverflow.com/questions/5131131/what-happens-when-you-increment-an-integer-beyond-its-max-value)
你之所以看到第一个显示的值是 400000
,是因为循环运行非常快,控制台无法正常处理,因此你只看到了部分输出。
不确定你的目标是什么,但要使此程序产生不同的结果,要么更改循环条件,要么在循环内部添加 break
语句,正如评论中所提到的。
英文:
The only way that the loop could be exited in normal circumstances, is if num
became 0
. But you never reassign num
to any other number, so it is always 31
, so the loop won't end (in a regular manner).
What happens though is in your loop you're incrementing j
on every pass. j
is declared an int. int
s have maximum values defined, after which they go to minimum value, so from maximum (positive) number, after another increase you get a minimum (negative) number. Then you count up till you reach 0
. And then the exception is thrown as the application tries to divide by 0
.
(see here: https://stackoverflow.com/questions/5131131/what-happens-when-you-increment-an-integer-beyond-its-max-value)
The reason you see 400000
as the first displayed value is because the loops go so fast, that the console is not able to handle it gracefully, and you see just some of the outputs displayed.
Not sure what you're trying to achieve, but in order for this program to work differently, either change the loop condition or add a break
statement inside - as mentioned in the comments.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论