0
import java.util.Scanner;

public class PowersOf2
{
    public static void main(String[] args)
    {
        int inputPowersOf2;        
        int PowerOf2 = 1;   
        int exponent;
        int exponent2;

        Scanner scan = new Scanner(System.in);

        System.out.println("How many powers of 2 would you like printed?");
        inputPowersOf2 = scan.nextInt();
        System.out.println("\n\n");
        if(inputPowersOf2 >= 2)
        {
            System.out.println("Here are the first " + inputPowersOf2 + " powers of 2:");
            System.out.println();
        }
        else
        {
            System.out.println("Here is the first power of 2:");
            System.out.println();
        }

        exponent2 = 0;
        exponent = 0;
        while(exponent <= inputPowersOf2)
        {
            System.out.print("2^" + exponent2 + " = ");
            exponent2++;
            System.out.println((PowerOf2 = 2 * PowerOf2) / 2);
            exponent++;
        }
    }
}

为什么当我说给我 2 的 1 次方时它会打印

2^0
2^1

当我说给我 2 的 2 次方时,它会打印

2^0
2^1
2^2

等等...

4

2 回答 2

1

代替

while(exponent <= inputPowersOf2)

while(exponent < inputPowersOf2)

正如其他人在评论中所说,使用调试器非常非常容易解决。

希望有帮助,

于 2013-10-07T08:14:34.777 回答
0

您可以使用小的输入在纸上手动追溯这些步骤,然后继续进行更大的输入。

只需替换代码 while(exponent <= inputPowersOf2) 因为“=”符号它会运行额外的时间。

于 2013-10-07T08:28:58.983 回答