题16:
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
这道题主要是考察代码的完整性,处理好各种异常
public class Power {
public static double Power(double base, int exponent) throws Exception {
if(base == 0 && exponent >= 0){
return 0;
}
if(base == 0 && exponent < 0){
throw new Exception("0不能求倒数~");
}
double result = 1;
if(exponent > 0){
for(int i = 1;i <= exponent;i++){
result *= base;
}
}
if(exponent < 0){
for(int i = 1;i <= (0 - exponent);i++){
result *= base;
}
result = 1 / result;
}
return result;
}
//test
public static void main(String[] args) throws Exception {
System.out.println(Power(2,-2));
}
}