程序计算能力为2

Tua*_*yen 1 java math loops

我正在编写一个简单的程序来计算2的幂.用户输入他们想要计算2的幂的次数,假设用户输入4,我的程序将返回2,4,8,16.这里是代码

import java.util.Scanner;

public class PowersOf2

{

public static void main(String[] args)

{

int numPowersOf2;        
//How many powers of 2 to compute

int nextPowerOf2 = 1;    
//Current power of  2

int exponent = 0;            

//Exponent for current power of 2 -- this

//also serves as a counter for the loop

Scanner scan = new Scanner(System.in);

        System.out.println("How many powers of 2 would you like printed?");
        numPowersOf2 = scan.nextInt();

        //print a message saying how many powers of 2 will be printed
        //initialize exponent -- the first thing printed is 2 to the what?

    System.out.println("Here are the first " + numPowersOf2 + " power of 2");


      while (exponent<numPowersOf2)
        {
          //print out current power of 2

            nextPowerOf2=nextPowerOf2*2;

            exponent++;

            System.out.println(nextPowerOf2);
            //find next power of 2 -- how do you get this from the last one?

            //increment exponent
             }
        }
}
Run Code Online (Sandbox Code Playgroud)

如果我希望它从0开始首先说2 ^ 0 = 1,那么如果用户输入4,它将返回1,2,4,8而不是2,4,8,16.如何修改它以获得它?

use*_*421 5

2 n ==(1 << n); 0 <= n <32