题目描述 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
Java代码:
代码语言:javascript复制public class Solution {
public double Power(double base, int exponent) {
double result = 1.0;
if ( exponent == 0.0){
return 1.0;
}else if ( exponent > 0){
for(int i = 0 ; i < (int)(exponent) ; i ){
result *= base;
}
}else{
if ( base == 0){
throw new RuntimeException("分母不能为0");
}
exponent = -exponent;
for ( int i = 0 ; i < exponent ; i ){
result *= base;
}
result = 1/result;
}
return result;
}
}
C 代码:
代码语言:javascript复制#include <cmath>
using namespace std;
class Solution {
public:
int equal(double a,double b){
return fabs(a-b) < 0.000001;
}
double Power(double base, int exponent) {
# 0的0次幂没有意义,因此要把base为0的情况排除在外
# 浮点数的相等需要利用函数,而不是base == 0.0这样的语句
if(exponent == 0 && !this->equal(base,0.0)){
return 1.0;
}
int n = (exponent>0)?exponent:-exponent;
double result = 1.0;
for(int i = 1 ; i <= n ; i ){
result *= base;
}
return (exponent>0)?result:1.0/result;
}
};