數值的整數次方

數值的整數次方

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

c語言中有一個pow函數可以求得數的乘方。

基本實現:

1 double Power(double base,int exponent)
2 {
3     double result=1.0;
4     for(int i=1;i<=exponent;++i)
5     {
6         result*=base;
7     }
8     return result;
9 }

考慮不全面的地方:1、exponent小於1(0或者負數怎麼辦?)

         2、0的0次方是幾?(數學上未曾明確的定義1 or 0都可以)

         3、效率是否很高?

 1 #include<iostream>
 2 using namespace std;
 3 bool InvalidInput = false;
 4 bool equals(double num1, double num2)
 5 {
 6     if (num1 - num2<0.0000001&&num1 - num2>-0.0000001)
 7         return true;
 8     return false;
 9 }
10 double PowerNormal(double base, unsigned int exponnent)
11 {
12     double result = 1.0;
13     for (int i = 1; i <= exponnent; ++i)
14     {
15         result *= base;
16     }
17     return result;
18 }
19 double Power(double base, int exponent)
20 {
21     InvalidInput = false;
22     if (equals(base, 0.0) && exponent < 0){
23         InvalidInput = true;
24         return 0.0;
25     }
26     unsigned int Normalexponent = (unsigned int)(exponent);
27     if (exponent < 0)
28     {
29         Normalexponent = (unsigned int)(-exponent);
30     }
31     double result=PowerNormal(base, Normalexponent);
32     if (exponent < -1){
33         result = 1.0/ result;
34     }
35     return result;
36 }
37 int main()
38 {
39     cout << Power(2.5, 2) << endl;
40     cout << Power(9.3, -4) << endl; 
41     cout<< Power(0, 0) << endl;
42 
43     system("pause");
44     return 0;
45 }

更高效的Power函數

 

 1 double PowerunsignedExponent(double base, unsigned int exponent)
 2 {
 3     if (exponent == 0)
 4         return 1;
 5     if (exponent == 1)
 6         return base;
 7     double result = PowerunsignedExponent(base, exponent >> 1);
 8     result *= result;
 9     if (exponent & 0x1 == 1)
10         result *= base;
11     return result;
12 }

 

posted @ 2016-04-22 23:57 General_up 閱讀(...) 評論(...) 編輯 收藏
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章