看似无限循环终止,除非使用 System.out.println [英] Seemingly endless loop terminates, unless System.out.println is used

查看:33
本文介绍了看似无限循环终止,除非使用 System.out.println的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段简单的代码,应该是一个无限循环,因为 x 会一直增长并且总是大于 j.

I had a simple bit of code that was supposed to be an endless loop since x will always be growing and will always remain larger than j.

int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
   x = x + y;
}
System.out.println(y);

但照原样打印 y 并且不会无限循环.我不明白为什么.但是,当我按以下方式调整代码时:

but as is, it prints y and does not loop endlessly. I cannot figure out why. However, when I adjust the code in the following manner:

int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
    x = x + y;
    System.out.println(y);
}
System.out.println(y);

它变成了一个无限循环,我不知道为什么.java 是否识别出它的无限循环并在第一种情况下跳过它,但必须在第二种情况下执行方法调用才能按预期运行?困惑:)

It becomes an endless loop and I have no idea why. Does java recognize its an endless loop and skip it in the first situation but has to execute a method call in the second so it behaves as expected? Confused :)

推荐答案

这两个例子都不是无穷无尽的.

Both of the examples are not endless.

问题在于 Java(或几乎任何其他通用语言)中 int 类型的限制.当x的值达到0x7fffffff时,加任何正值都会导致溢出,x变为负数,因此低于j.

The issue is the limitation of int type in Java (or pretty much any other common language). When the value of x reaches 0x7fffffff, adding any positive value will result in overflow and the x becomes negative, therefore lower than j.

第一个和第二个循环之间的区别在于内部代码需要更多的时间,并且可能需要几分钟直到 x 溢出.对于第一个示例,它可能需要不到一秒钟的时间,或者很可能代码将被优化器删除,因为它没有任何效果.

The difference between the first and second loop is that the inner code takes much more time and it would take probably several minutes until x overflows. For the first example it may take less than second or most probably the code will be removed by optimizer as it doesn't have any effect.

正如讨论中提到的,时间在很大程度上取决于操作系统如何缓冲输出,是否输出到终端模拟器等,因此它可能比几分钟长得多.

As mentioned in the discussion, the time will heavily depend on how OS buffers the output, whether it outputs to terminal emulator etc., so it can be much higher than few minutes.

这篇关于看似无限循环终止,除非使用 System.out.println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆