题目描述
给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent,求 base 的 exponent 次方。
思路
主要是各种便捷条件,比如base=0,base<0 ,base=o时exponent<0等等
代码
public class Sixteen {
public double f1(double base,int exponent) throws Exception {
int absExponent = 0;
if(base==0.0&&exponent<0)
throw new Exception("底数为0且指数<0,错误参数");
else if(base<0.0)
throw new Exception("底数小于0,错误参数");
if(exponent<0) {
absExponent = -exponent;
double result = f2(base,absExponent);
result = 1.0/result;
return result;
}
double result = f2(base,exponent);
return result;
}
private double f2(double base,int exponent) {
double result = 1.0;
for(int i=1;i<=exponent;i++)
result *= base;
return result;
}
}