【发布时间】:2014-04-19 16:44:23
【问题描述】:
这是我的程序
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
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= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
问题是我不允许使用 math.pow 方法,我需要在 while 循环中找到另一种方法来获得正确答案。
【问题讨论】:
-
乘以可能?!?毕竟
next power = previous power * 2..eg2^1=22^2 = 4,2^3 = 4*2 = 8 -
一定要保存电源是否为负。如果是这样,除而不是乘。
-
获取您使用的指数
log,而不是pow。pow用于获取权限