Java “打印时的奇怪行为”;2的所有幂,适合于长的;

Java “打印时的奇怪行为”;2的所有幂,适合于长的;,java,for-loop,Java,For Loop,我试图打印从2^0开始的2的所有幂,这将适合一个长变量 这是到目前为止我的代码 long y = 0; int iteration = 1; for (y = 1; y < 9223372036854775807L; y *= 2) { System.out.println("2 to the power of " + iteration + " is " +y); iteration++; 然后程序不断地返回 2 to the

我试图打印从2^0开始的2的所有幂,这将适合一个长变量

这是到目前为止我的代码

    long y = 0;
    int iteration = 1;
    for (y = 1; y < 9223372036854775807L; y *= 2) {

        System.out.println("2 to the power of " + iteration + " is " +y);
        iteration++;
然后程序不断地返回

2 to the power of 64 is 0
2 to the power of 65 is 0
2 to the power of 66 is 0
等等


这里发生了什么?

当执行最后的
y*=2
y
变成一个大于可存储为长时间的值。在java中,long是2的补码,其中最高有效位表示一个数字是正的还是负的,当您使long大于其最大值时,最高有效位从0变为1,这意味着long的值变为负,因此循环永远不会终止。有一个关于二的补码的好视频可以更好地解释。

y<9223372036854775807L
相当于“在溢出发生后检查溢出”好吧,我对这一点相当陌生,但我最终将其改为(y=1;y0;y*=2){这会给出所需的结果,您可以删除它“y2 to the power of 64 is 0 2 to the power of 65 is 0 2 to the power of 66 is 0