面試題11 數值的整數次方的計算

2021-07-13 14:35:00 字數 1169 閱讀 9574

1.在不用庫函式的情況下,實現函式 double power(double base,double exponent),就是求base的exponent次方。

分析:要考慮全面,可能出現的異常情況,例如當指數為負數,底數為0的情況,相當於是除以0,出產生異常,當底數為負數的時候,應該是先取絕對值,最後再求導數。

通常的做法是迴圈相乘法,但是這種效率並不是最高的,可以借用二分查詢裡面的思想,遞迴的計算2/exponent次方的值,再求平方,這樣可以減少計算量。

原始碼:

/*  */

#include#include #include using namespace std;

//#define one

#define two

bool g_invalidinput = false;//全域性標誌位

bool equal(double num1, double num2);

double powerwithunsignedexponent(double base, unsigned int exponent);

double power(double base, int exponent)

unsigned int ab***ponent = (unsigned int)(exponent);

if (exponent < 0)

ab***ponent = (unsigned int)(-exponent);

double result = powerwithunsignedexponent(base, ab***ponent);

if (exponent < 0)

result = 1.0 / result;

return result;

}#ifdef one

double powerwithunsignedexponent(double base, unsigned int exponent)

#elif defined two

double powerwithunsignedexponent(double base, unsigned int exponent)

#endif

bool equal(double num1, double num2)//浮點數比較是否為0

int main()

面試題11 數值的整數次方

題目 實現函式double power double base,int exponent 求base的exponent次方。不得使用庫函式,同時不需要考慮大數問題。這道題目有以下幾點需要注意 0的0次方是無意義的,非法輸入 0的負數次方相當於0作為除數,也是無意義的,非法輸入 base如果非0,如果...

面試題11 數值的整數次方

面試題11 題目 實現函式double power double base,int exponent 求base的exponent次方。不使用庫函式,不考慮大數問題。需要考慮的是當輸入的指數 exponent 為0或負數的情況。bool g invalidinput false 採用全域性變數來標識...

面試題11 數值的整數次方

這個問題我想很多人拿到之後直接設定乙個for迴圈,讓底數自乘次方和次數就行。但是沒有考慮到底數是0 指數是0 以及指數是負數的情況 coding utf 8 不得使用庫函式,實現數值的整數次方 def power base,exponent answer 1.0 if isequaltozero b...