/**
 * @Name:
 * @Description:
 * @Author: Allen
 */
public class PowerCalculate16 {
    public static void main(String[] args) {
        Solution16 solution16= new Solution16();
        System.out.println(solution16.Power(3.4, -2));
    }
}

class Solution16 {
    public double Power(double base, int exponent) {
        if(base==0 && exponent<0){//底数为0,抛出异常
            throw new RuntimeException("0 can not be denominator");
        }
        int absNum=exponent;
        if(exponent<0)//考虑到指数为负数的情况
            absNum=-exponent;
        double result=calculatePower(base,absNum);
        if(exponent<0) result=1/result;
        return result;
  }
    
   private double calculatePower(double base, int exponent){
       double result=1;
       for(int i=1; i<=exponent; i++){
           result*=base;
       }
       return result;
   }
}

 

相关文章:

  • 2022-12-23
  • 2021-09-14
  • 2021-08-09
  • 2021-06-07
  • 2022-02-11
  • 2021-10-04
  • 2021-12-20
猜你喜欢
  • 2021-05-26
  • 2021-08-01
  • 2022-12-23
  • 2021-05-22
相关资源
相似解决方案