Java + = operator"在某个数字后停止添加"

时间:2013-07-19 20:40:35

标签: java

+ =产生不同的结果,请参阅下面的代码...使用temp的代码正常工作而不是另一个可以通过创建Java应用程序来调试它。

public long JavaStopsAdding(int treeHeight) {

    long cars = 0;
    long cars1 = 0;
    int i = 0;
    while (treeHeight - i >= 0) {

        long temp = 0;

        if (treeHeight - i == 0 ) {
            cars += 1;
            cars1 += 1;
            break;
        }


       // working code start

           temp = (long) ((Math.pow(2,treeHeight- i))/2);
       cars1 += temp;
           System.out.print("temp " + (treeHeight- i) + " cars " + cars1 +"\n");
    // working code END

          // NON working code Start
            cars += ((Math.pow(2,treeHeight- i))/2);
    System.out.print("temp " + (treeHeight- i) + " cars " + cars + "\n");   
        // NON working code END
        i += 2;     
    }
    return cars;
}

3 个答案:

答案 0 :(得分:4)

很可能+ =没有错。相反,问题是你的价值已经溢出。

您不应该使用Math.pow(2, n),而是使用1L << n,这不仅更快,而且更有可能发挥作用。无论哪种方式,你都不能有n&gt; 62并希望这可行。

答案 1 :(得分:1)

使用BigInteger作为数学运算导致它溢出。

答案 2 :(得分:-1)

我已经使用treeheight = 10测试了代码并找到了一切正常的代码。你的代码包含两个变量cars1和cars:

// working code start

temp = (long) ((Math.pow(2,treeHeight- i))/2);
cars1 += temp;
System.out.print("temp " + (treeHeight- i) + " cars " + cars1 +"\n");
// working code END

 // NON working code Start
        cars += ((Math.pow(2,treeHeight- i))/2);
System.out.print("temp " + (treeHeight- i) + " cars " + cars + "\n");   
    // NON working code END