演算法 數值的整數次方

2021-08-27 05:02:24 字數 1979 閱讀 1078

從三方面確保**完整性

[1]功能測試

測試程式能否按預期完成功能。

[2]邊界測試

測試一些輸入的邊界,看看程式還能不能正常執行。

[3]負面測試

測試一些不合法的輸入,檢驗程式的魯棒性。魯棒性實際上就是程式能很好承受使用者的各種輸入(操作也是輸入)的性質,即便要求了正確使用的輸入,也要考慮到其它錯誤的輸入,一般在程式中做特殊判斷。

三種錯誤處理的方法

[1]返回值

用特殊的返回值來告訴呼叫者是否出錯。優點是和系統api一致,缺點是不容易使用返回結果。

[2]全域性變數

當錯誤發生時去修改全域性變數。優點是到處都可以直接使用,缺點是使用者經常會忘記檢查全域性變數。

[3]丟擲異常

c語言中沒有,c++裡也支援異常,這是各個高階語言強烈推薦的處理方式。優點是正常執行的try塊和處理錯誤的catch塊邏輯劃分清晰,缺點是丟擲異常時程式的執行會打亂正常的順序,對程式效能有很大影響。

面試題16:數值的整數次方

實現函式double power(double base, int exponent),求base的exponent次方。不得使用庫函式,同時不需要考慮大數問題。

實際上就是要求實現乙個pow函式,需要注意各種特殊情況,單獨拿出來判斷一下就可以了。程式裡還用了快速冪,移位等操作。

#include

using

namespace std;

bool g_invalidinput =

false

;//標識出錯的全域性變數,出錯時設為true

bool

equal

(double num1,

double num2)

;double

powerwithunsignedexponent

(double base,

unsigned

int exponent)

;// 引數:

// base: 底數

// exponent: 指數

// 返回值:

// base的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;

}// 引數:

// base: 底數

// exponent: 正指數

// 返回值:

// base的exponent次冪

double

powerwithunsignedexponent

(double base,

unsigned

int exponent)

//輸入兩個浮點數,只要它們的差值足夠小即可判斷為相等,返回是否相等

bool

equal

(double num1,

double num2)

intmain()

演算法 數值的整數次方

給定乙個double型別的浮點數base和int型別的整數exponent。求base的exponent次方。注 base和exponent不同時為0。當exponent 0時,本題的本質就是快速乘法。當exponent 0時,bas eexp onen t 1b ase expo nent bas...

常見演算法 數值的整數次方

package common author zhaoliang program newcoder description 數值的整數次方 create 2020 11 21 19 52 public class power int ab ponent exponent 指數小於0時,先轉成正數計算 ...

PHP 演算法 數值的整數次方的PHP實現

給定乙個double型別的浮點數base和int型別的整數exponent。求base的exponent次方。思路 1.指數的二進位制表達10 6次方 可以表示10 110 二進位制 10 100 10 10 10 000 10 4 10 2 2.移位運算 while n 0 function po...