Я пишу простую программу для вычисления мощности 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
}
}
}
Если я хочу, чтобы он начинался с 0, сначала скажем как 2 ^ 0 = 1, поэтому, если пользователь введет 4, он вернет 1,2,4,8 вместо2,4,8,16.Как мне изменить это, чтобы получить это?