Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

Unbelievable result when subtracting in a loop in Java (Windows only?)

I use windows 10, jdk 1.8.0_191.

I use this code to test my program:

public class Unbelievable {
    public void test() {
        int a = 5;
        while ((a -= 2) > 0){
            //nothing to do
        }
        System.out.println("result= " + a);
    }

    public static void main(String[] args) {
        Unbelievable un = new Unbelievable();
        for (int i = 0; i < 2000_0; i++) {
            un.test();
        }
    }
}

When I run the code. The output likes this:

result= -1
result= -1
result= -1
result= -1
……
result= /
result= /
result= /
result= /
result= /
result= /
result= /
result= /
result= /

There are 12821 result= -1 and 7179 result= /, I don't understand why the result is like this.

I think all the result should be result= -1. But this result confused me.

@Steve added: Can anyone reproduce this who isn't on some version of Windows? How about a version of Windows other than 10? I think it will be valuable to narrow this down by platform if possible. The samples represented so far seem to me to suggest this a Windows-only thing, and possibly just a Windows 10 thing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I may have to disappoint you here:

javac Unbelievable.java && java Unbelievable | grep '-1' | wc -l

Rendered exactly 20000 for me.

Ran this on openjdk 11.0.10-ea 2021-01-19, Debian GNU/Linux, Kernel 5.10.9.

EDIT: so I punched this more than 50000 times. I would really appreciate if you could provide your OS and, especially, JDK version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...