java - 如何在不使用 math.pow for java 的情况下获取指数

标签 java math pow exponent

这是我的程序

// ************************************************************
    // 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 循环中获得正确答案。

最佳答案

2 的幂可以简单地计算为 Bit Shift Operators

int exponent = ...
int powerOf2 = 1 << exponent;

即使对于更一般的形式,您也应该不是 通过“乘以 n 次”来计算指数。相反,你可以做 Exponentiation by squaring

关于java - 如何在不使用 math.pow for java 的情况下获取指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172704/

相关文章:

java - Spring Boot 在关闭时关闭 hibernate session - 在 @Async 方法完成之前

java - 在并行执行模拟中找到正确的随机种子数

java - 具有同步功能的单例类和静态同步功能有什么区别

c - Pow:对重载函数的模糊调用

c# - RSA - Math.pow 不准确

java - 如何在具有随机大小和随机坐标的画圆内绘制字母?

ruby - 三角形坐标计算

algorithm - 如何获得每个有效点的法线向量?

c - gcc 似乎找不到数学库

php smarty 计算费率