数值的整数次方

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <exception>
 4 #include <stack>
 5 /*
 6     题目:实现函数 doublePower(double base,int exponenet),
 7     求base的exponenet次方,不得使用库函数,同时不需要考虑大数问题
 8 */
 9 using namespace std;
10 bool g_InvalidInput = false;
11 bool equal(double num1,double num2)
12 {
13     if((num1 - num2 >-0.0000001)&&(num1-num2<0.0000001))
14     {
15         return true;
16     }
17     else return false;
18 }
19 double PowerWithUnsignedExponenet(double base,unsigned int exponent)
20 {
21     double result = 1.0;
22     for(unsigned int i = 1;i<=exponent;++i)
23     {
24         result*= base;
25     }
26     return result;
27 }
28 double Power(double base,int exponent)
29 {
30     g_InvalidInput = false;
31     if(equal(base,0.0)&&exponent<0)
32     {
33         g_InvalidInput = true;
34         return 0.0;
35     }
36 
37     unsigned int absExponent = (unsigned int) (exponent);
38     if(exponent<0)
39         absExponent = (unsigned int)(-exponent);
40     double result = PowerWithUnsignedExponenet(base,absExponent);
41     if(exponent <0)
42         result = 1.0/result;
43     return result;
44 }
45 
46 int _tmain(int argc, _TCHAR* argv[])
47 { 
48     cout<<Power(2,3)<<endl;
49     return 0 ;
50 }
原文地址:https://www.cnblogs.com/crazycodehzp/p/3561275.html