/*
给定一个double类型的浮点数base和int类型的整数exponent。
求base的exponent次方。不得使用库函数,不需要考虑大数问题。
注意事项:不能用==比较两个浮点数是否相等,因为有误差。考虑输入值的多种情况。
*/
public class Class14 {
public double Power(double base, int exponent){
double result = 0;
if(Equals(base,0)){
return 0.0;
}
if(Equals(exponent,1)){
return 1.0;
}
if(exponent > 0){
result = Culculate(base, exponent);
}else if(exponent < 0){
result = Culculate(1/base, -exponent);
}
return result;
}
public double Culculate(double base, int exponent){
double sum = 1.0;
for(int i = 1; i <= exponent; i++){
sum = sum * base;
}
return sum;
}
public boolean Equals(double n1, double n2){
if((n1 - n2 < 0.00000001) && (n1 - n2 > -0.00000001)){
return true;
}else{
return false;
}
}
public void test1(){
double base = 2.0;
int exponent = 3;
System.out.println(Power(base,exponent));
}
public void test2(){
double base = 3.0;
int exponent = 4;
System.out.println(Power(base,exponent));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Class14 c = new Class14();
c.test1();
c.test2();
}
}