英文:
for loop query in java
问题
这段代码的输出如下:
1521760
1521761
1521762
1521763
1521764
1521765
1521766
1521767
1521768
1521769
1521770
1521783
1521784
请问有人可以解释为什么它不是无限次打印0,而是打印这些随机数字吗?
英文:
for(int x=0;; ) {
System.out.println(x);
x++;
}
The o/p of the code is as below:
1521760
1521761
1521762
1521763
1521764
1521765
1521766
1521767
1521768
1521769
1521770
1521783
1521784
Can anyone please explain instead of printing 0 for infinite times why this is printing these random numbers?
答案1
得分: 3
以下是翻译好的部分:
这是从0一直打印到最高值。但是处理器运行非常快(已经运行到1521760),所以您直接开始看到这些高值。
您可以通过添加断点(或在x++
行中设置断点进行调试)来检查,如下所示:
for (int x = 0;;) {
System.out.println(x);
x++;
if (x == 10)
break;
}
//输出如下
0
1
2
3
4
5
6
7
8
9
进程以退出代码0完成
英文:
It is printing from 0 to all the way up. But processor runs so fast (it has already ran until 1521760), so you directly start seeing from those high values.
You can check by putting break (or doing debugging by putting breakpoints in x++
line) as below,
for(int x=0;; ) {
System.out.println(x);
x++;
if(x == 10)
break;
}
//output as
0
1
2
3
4
5
6
7
8
9
Process finished with exit code 0
答案2
得分: 0
因为你在for循环块内增加了变量x。尽管如此,在循环语句内部你没有增加x。
英文:
Because you are incrementing variable x inside for loop block. Although, you not increment x inside loop statement.
答案3
得分: 0
以下是翻译好的部分:
"如果在不同的机器上运行相同的代码(具有不同的处理器),那么得到的数字很可能会不同,但这并不是因为它们是随机数。这是因为处理器的速度差异。所以通常处理器以我们无法想象的速度处理程序。因此,即使在这里,您的处理器已经将您的值递增到某个限制,这就是为什么您看到类似的现象的原因。您可以通过在特定条件下中断代码来检查这一点,就像在上面的回答中所示。但是,通过调试代码,您可以以更详细的方式查看那里正在发生的增量过程。然后,您可以看到x的递增过程。"
英文:
It's not a random number if you run the same code in a different machine(Which has a different processor) most probably you will get a different number, but it's not because they are Random numbers. It's because of the processors' speed difference.So normally processors process programs at a speed that we can't even think, So here also your processor already incremented your value up to a certain limit that's why you see something like that.you can check it by breaking the code in a particular condition like in the above answer. But you can see what's happening there in a much more detailed manner by debugging the code. Then you can see the incrementing process of x
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论