没有math.pow的指数使用for循环(在java中)

时间:2016-03-03 21:17:53

标签: java

我需要输入2个输入的数字并将变量1计算为变量2的幂,而不使用math.pow并使用for循环。这就是我现在所拥有的

UserModel

}

如果指数为0,它似乎只能起作用,否则它只显示一个值。我需要积极和消极的指数。提前谢谢!

4 个答案:

答案 0 :(得分:2)

b <0的情况仅对浮点数有意义,因此我将a的类型和返回值更改为double

public static double mathPower(double a, int b) 
{
    double result = 1;

    if (b < 0) {
       a = 1.0 / a;
       b = -b;
    }

    for (int  i = 0; i < b; i++) {
        result = result * a;
    }

    return result;
}

答案 1 :(得分:2)

您有三个主要问题:

  
      
  1. 循环中的return语句在第一次重复时就会破坏它。

  2.   
  3. 您正在使用a变量作为循环变量。

  4.   
  5. 如果您允许使用负指数,则返回值应为双倍。

  6.   
    public static double mathPower(double a, int b)
    {
        double result = 1.0;

        if (b == 0)
        {
            result = 1.0;
        }

        if (b < 0)
        {
            a = (1.0 / a);
            b = -b;
        }

        for (int i = 0; i < b; i++)
        {
            result = result * a;
        }

        return result;
    }

答案 2 :(得分:1)

  

假设你有numb1 = 2和numb2 = 6。        然后

temp=1;   
 if (numb2 < 0) {
       numb1 = 1 / numb1;
       numb2 = -numb2;
    }

    for(int n = 1; n<=numb2; n++){
        temp=temp*numb1;
        }

答案 3 :(得分:-1)

public double power(double base,int pow)
{
    double result = 1;
    if(pow==0)
       return 1;
    if(base == 0)
       return 0;
    if(pow>0)
    {
         for(int i = 0;i<pow;i++)
         { 
              result *= base;
         }
    }
    else
    {
      for(int i = pow;i<0;i++)
         { 
              result *= base;
         }
           result = 1/result;
    }
    return result;
}
相关问题