考慮要全面;
底數(shù)和指數(shù)都是0,無意義。其中相等不能用==;
指數(shù)大于0,迭代乘;
小余0;
代碼實現(xiàn):
package com.mytest.mymain;public class MyPower001 { public static void main(String[] args) { MyPower001 myPower001=new MyPower001(); System.out.PRintln("Main: "+myPower001.Power(2, -3)); } private boolean myequal(double a , double b){ if(a-b<0.0000001 && a-b>-0.0000001){ return true; }else{ return false; } } private double unsignpower(double base, int exponent){ double result=1.0; for(int i=1;i<=exponent;i++){ result=result*base; } return result; } public double Power(double base, int exponent) { double result=0.0; if(myequal(base,0.0) && exponent<0) return 0.0; if(exponent<0){ result=1.0/unsignpower(base,-exponent); }else if(exponent>0){ result=unsignpower(base,exponent); }else if(exponent==0){ return 1.0; } return result; } } 改進: 求指數(shù)有個快速迭代的公式:a^n=a^(n/2)*a^(n/2) 偶數(shù) a^n=a^[(n-1)/2]*a^[(n-1)/2] 奇數(shù)
新聞熱點
疑難解答