整数幂程序 Java 需要帮助

Integer powers program Java help needed

所以我在我的书中得到了这个程序并对其进行了测试,它运行良好。我需要帮助,虽然了解它是如何工作的。我知道两种方式的力量,例如 2x2x2x2x2x2x2x2x2 = 512。好吧,这是程序:

// Compute integer powers of 2.
class Power {
    public static void main(String args[]) {
        int e;
        int result;
        for(int i=0; i < 10; i++) {
            result = 1;
            e = i;
            while(e > 0) {
                result *= 2;
                e--;
            }
            System.out.println("2 to the " + i + " power is " + result);
         }
     }
}

所以我了解到 result *=2 表示:result = result * 2。我不明白它是如何工作的。例如,i 现在是 4。结果再次 = 1,e=i,所以 e 现在是 4。4 高于 0,因此 while 循环运行。然后它说的结果是result * 2,但是1=1 * 2 = 2。但是结果应该是16。这里的result怎么变成16呢?因为它一直是 1。我不明白。另外,为什么是电子部分?我已经尝试过使用 e++ 的程序,但随后它将结果打印为 1,此后仅打印 0。也尝试过完全不使用 e-- 或 e++,但随后它在 dos 提示符下冻结。请注意,我是初学者,这是我的第一个 while 循环。如果有任何帮助,我将不胜感激。

while(e > 0) {
    result * = 2;
    e--;
}

这个循环一直执行到e变为零。 所以在第一个循环中

result = 1 * 2;

在第二个循环中

result = result * 2; 表示 result = 2 * 2

同样。

您正在使用嵌套循环。即,while 循环内嵌 for 循环。这意味着对于 for 循环的每次迭代,while 循环将执行直到它的条件变为假。

现在回答您的问题,对于 for 的第一次迭代,i = 0。这意味着 e = 0,这反过来意味着 while 循环将不会执行。所以,这里的结果是 1,这是合乎逻辑的,因为任何 n^0 = 1.

对于for的第二次迭代,i = 1。这意味着e = 1。这里,while循环将运行进行1次迭代。它将使 result = 2 (result *= 2)。所以,结果是 2,因为 2^1 = 2。

下面是干货-运行table.


for  i    while    e    result
loop      loop
1    0    1        0    1  
2    1    1        1    2
3    2    1        2    2
     1    2        1    4
4    3    1        3    2
     2    2        2    4
     1    3        1    8

等等。这个table看似丑陋,但它会给你一个提示。

How does result changes here to 16? Because it is 1 all the time.

结果 初始化为 1,但每次 while 循环执行时它的值都会相乘。

I've tried the program with e++, but then it prints result as 1 and after this only 0.

如果你用e++代替e--,这个循环会运行直到e溢出。但是当 e 的值达到 33 时,结果将因乘法而变为 0。之后,它将保持为 0。

Also tried it without e-- or e++ at all, but then it freezes in the dos-prompt.

这意味着你的 while 循环条件永远不会变为假,因此,它将是一个无限循环。