1

我需要编写一个名为的方法pow2,它接受一个实数基数和一个整数指数作为参数。它应该将升高的底座恢复到给定的功率。您的代码应该适用于正指数和负指数。例如,调用pow2(2.0, -2)返回0.25. 不要在您的解决方案中使用 Math.pow。

这是我到目前为止所拥有的:

public double pow2(double x,int y){
    double total=1;
    for(int i=1;i<=y;i++){
        total*=x;
    }
    return total;
}

但问题是当我尝试调用时pow(2.0, -2),它会返回 1.0。我该如何实现这个方法?

4

4 回答 4

3

你必须分支,这取决于你是负值还是正值。

这是一个适用于递归的版本:

public double pow2(double x,int y){
    return _pow2(1.0, x, y);
}

private double _pow2(double res, double x, int y) {
    if (y < 0) return _pow2(res/x, x, y+1);
    if (y > 0) return _pow2(res*x, x, y-1);
    return res;
}

如果y太大或太小,那么您将遇到堆栈溢出,因此将其更改为非递归函数留给操作。

编辑:关于你的最后一个问题,你将结果设置为1.0,循环的主体从未使用过,因为!(1 <= -2),所以你返回未修改的结果1.0

于 2013-03-09T12:06:41.013 回答
1

好吧,最后,如果您想以迭代的方式进行操作,只需先检查y是正数还是负数。

public double pow2(double x, int y)
{
    double total = 1.0;

    if(y > 0)
    {
        for(int i = 1 ; i <= y ; i++)
        {
            total *= x;
        }
    } 
    else 
    {
        for(int i = -1 ; i >= y ; i--)
        {
            total /= x;
        }
    }
    return total;
}
于 2013-03-09T12:20:50.387 回答
-1
public static double pow2(double x,int y){
    double total=1;
    if(y>0){
    for(int i=1;i<=y;i++){
        total*=x;
    }
    return total;
    }
    else if (y<0){
        double temp=1/x;//this makes 2 as 1/2
        y=y*-1;         //to have a meaningful iteration if for loop
        for(int i=1;i<=y;i++){
            total*=temp;
        }   
        return total;
    }else
        return 1;
}
于 2013-03-09T12:23:51.440 回答
-1
public static void main(String[] args) {

    System.out.println(pow2(2,3));

}

public static double pow2(double x,int y){
    double total=1;
    for(int i=1;i<=y;i++){
        total*=x;
    }
    return total ;
}
于 2013-03-09T12:04:17.183 回答