题目描述
给定一个double类型的浮点数base,和一个int类型整数exponent
求:
base的exponent的次方
题目分析
1、首先判断base和exponent是否合法?0的负数次幂不合法,0的0次方默认为0
2、考虑exponent正负,如果为负数,base为特别小特别小的小数,则直接跑出异常,0的负数次幂是没有意义的
代码实现
private double power(double b, int e) throws Exception {
double result = 0.0;
if (equals(b, 0.0) && e < 0) {
throw new Exception("0的负数次幂没有意义");
}
if (e < 0) {
result = 1.0 / (powerWithExponent(b, -e));
}
if (e > 0) {
result = powerWithExponent(b, e);
}
return result;
}
private double powerWithExponent(double base, int exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base;
double result = 1.0;
for (int i = 1; i <= exponent; i++) {
result = result * base;
}
return result;
}
public boolean equals(double b1, double b2) {
if ((b1 - b2) >= -0.0000001 && (b1 - b2) > 0.0000001) return true;
else return false;
}