+= 产生不同的结果,请参见下面的代码...带有 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;
}