use*_*056 5 java math exponent pow
这是我的计划
// ************************************************************
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我不允许使用math.pow方法,我需要找到另一种方法来在while循环中获得正确的答案.
2的幂可以简单地由位移算子计算
int exponent = ...
int powerOf2 = 1 << exponent;
Run Code Online (Sandbox Code Playgroud)
即使对于更一般的形式,也不应该通过"乘以n时间" 来计算指数.相反,你可以通过平方来做Exponentiation
如果没有性能限制,您可以执行以下操作:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
Run Code Online (Sandbox Code Playgroud)