我正在编写一个简单的程序来计算2的幂。用户输入他们想要计算2的幂的次数,假设用户输入4,我的程序将返回2,4,8,这是代码
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。如何修改它以获得它?
答案 0 :(得分:5)
2 n ==(1 <&lt; n); 0&lt; = n&lt; 0 32
答案 1 :(得分:3)
只需在更改之前打印nextPowerOf2
。
while (exponent<numPowersOf2)
{
System.out.println(nextPowerOf2);
nextPowerOf2=nextPowerOf2*2;
exponent++;
}
答案 2 :(得分:1)
只能在乘以2之前打印该值。
//print out current power of 2
System.out.println(nextPowerOf2);
nextPowerOf2=nextPowerOf2*2;
exponent++;
答案 3 :(得分:0)
首先打印,然后更新。只需重新安排操作:
while (exponent<numPowersOf2)
{
//print out current power of 2
System.out.println(nextPowerOf2);
//find next power of 2
nextPowerOf2=nextPowerOf2*2;
//increment exponent
exponent++;
}
现在在合理的地方也有正确的缩进和评论!
顺便说一下,使用for
循环编写它更有意义:
for (int exponent = 0; exponent < numPowersOf2; ++exponent) {
//print out current power of 2
System.out.println(nextPowerOf2);
//find next power of 2
nextPowerOf2=nextPowerOf2*2;
}
答案 4 :(得分:0)
nextPowerOf2 = 1;
exponent = 0;
do
{
System.out.println(nextPowerOf2);
nextPowerOf2=nextPowerOf2*2;
exponent++;
}
while( exponent < numPowersOf2 );
应该这样做。
答案 5 :(得分:0)
试试这些?它们速度非常快,适合大多数前期,当前和下一个需求。
编辑:注意到你希望它打印出所有,你可以做的是while循环添加打印输出。
public static int getPowerOfTwo(int size)
{
int n = -1;
while (size >> ++n > 0);
return (1 << n - 1 == size) ? size : 1 << n;
}
public static int getNextPowerOfTwo(int size)
{
int n = -1;
while (size >> ++n > 0);
return 1 << n;
}
public static int getPreviousPowerOfTwo(int size)
{
int n = -1;
while (size >> ++n > 0);
return 1 << n - 1;
}
万一你无法弄明白,下面的内容应该有效。
public static void displayNextPowersOfTwo(int size)
{
int n = -1;
while (size >> ++n > 0) {
System.out.print((1 << n) + ",");
}
System.out.print('\n');
}
答案 6 :(得分:0)
int numpowerof2 = 4, nextpower0f2 = 2, exponent = 0;
while(exponent < numpowerof2) {
System.out.println(nextpower0f2);
nextpower0f2 = nextpower0f2 * 2;
exponent++;
}
答案 7 :(得分:0)
而不是使用:
while (exponent < numPowersOf2)
使用此:
while (exponent <= numPowersOf2)
// <= will start with 0, which is 2^0=1