題目:實現double power(double base,int exponent),求base的exponent次方。不得使用庫函數,同時不需要考慮大數問題。
需要注意的地方:
1、指數爲負數時
2、底數爲零且指數爲負數時更快的方法:
當n爲偶數, a^n = a^(n/2) * a^(n/2)
當n爲奇數, a^n = a^((n-1)/2) * a^((n-1)/2)) * a
利用右移一位運算代替除以2
利用位與運算代替了求餘運算法%來判斷一個數是奇數還是偶數
import java.util.Scanner;
public class Power {
static boolean g_InvalidInput = false;
// base:底數
// exponent:指數
static double power(double base,int exponent) {
g_InvalidInput = false;
if(exponent == 0)
return 1.0;
if(exponent == 1)
return base;
// 當底數爲0,指數爲負時,需要做處理,不然會對0求倒數導致程序運行出錯
// 並且通過一個全局變量告訴函數的調用者出現了這個錯誤
if( equal(base, 0.0) && exponent < 0){
g_InvalidInput = true;
return 0.0;
}
// absExponent:底數的絕對值
int absExponent = exponent;
if( exponent < 0 )
absExponent = -absExponent;
/*//第一種方法
double result = 1.0;
for(int i = 1; i <= absExponent ; ++i)
result *= base;*/
//第二種方法
double result = PowerWithUnsignedExponent(base, absExponent);
if( exponent < 0 )
result = 1.0 / result;
return result;
}
//更快的方法
static double PowerWithUnsignedExponent(double base, int exponent){
if(exponent == 0)
return 1.0;
if(exponent == 1)
return base;
double result =PowerWithUnsignedExponent(base, exponent >> 1);
result *= result;
//按位做與運算,判斷一個數是奇數還是偶數,等於1爲奇數。
if( (exponent & 0x1) == 1)
result *= base;
return result;
}
//在計算機內表示小數時,都有誤差,所以不能用==判斷是否相等,只能判斷他們之差的絕對值是不是在很小的一個範圍內
static boolean equal(double num1,double num2) {
if( (num1 - num2) > -0.0000001 && (num1 - num2) < 0.0000001)
return true;
else
return false;
}
public static void main(String[] args) {
System.out.println("底數爲:");
Scanner sc1 = new Scanner(System.in);
double sc11 = sc1.nextDouble();
System.out.println("指數爲:");
Scanner sc2 = new Scanner(System.in);
int sc21 = sc2.nextInt();
System.out.println(sc11+"的"+sc21+"次方爲:"+power(sc11,sc21));
sc1.close();
sc2.close();
}
}