自己实现一个数的整数次方 11

注意输入的判断,多写几个if语句判断是否满足输入数据的条件

   

另外exp为负的时候,输入的base变为1.0/base而不是1/base

   

所以返回值要设置为doublebase也要设为double

   

另外要自己定义equal,而不能用==,要去判断两个数的差的绝对值是否在一定范围内

   

package myPower11;

   

public class MyPower11 {

static boolean equal(double num1,double num2)

{

if((num1-num2>-0.0000001)&&num1-num2<0.0000001)

{

return true;

}

else

{

return false;

}

}

static double myPower(double base, int exp) throws Exception {

double result = 0;

if (equal(base,0.0) && exp < 0) {

throw new Exception(“no sense”);

}

if (equal(base,0.0) && exp >= 0) {

return 0;

}

if (base!=0&&exp>=0) {

result=powerCal(base, exp);

return result;

}

if (base != 0 && exp < 0) {

return powerCal(1.0 / base, -exp);

}

return result;

   

}

   

static double powerCal(double base, int exp) {

double result = 1;

if (base != 0 && exp >= 0) {

for (int i = 0; i < exp; i++) {

result *= base;

}

   

}

return result;

   

}

   

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

System.out.println(myPower(2, -3));

}

   

}

   

    原文作者:keedor
    原文地址: https://www.cnblogs.com/keedor/p/4381296.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞