JZ-C-11

剑指offer第十一题:数值的整数次方

 1 //============================================================================
 2 // Name        : JZ-C-11.cpp
 3 // Author      : Laughing_Lz
 4 // Version     :
 5 // Copyright   : All Right Reserved
 6 // Description : 数值的整数次方
 7 //============================================================================
 8 
 9 #include <iostream>
10 using namespace std;
11 
12 bool equal(double num1, double num2);
13 double Power(double base, int exponent) {
14     double result = 1;
15     if (exponent > 0) {
16         if (equal(base, 0.0)) {
17             result = 0;
18         } else {
19             while (exponent > 0) {
20                 result = result * base;
21                 exponent--;
22             }
23         }
24     } else if (exponent == 0) {
25         if (equal(base, 0.0)) { //这里不能直接判断exponent == 0,原因:计算机内表示小数时都有误差,判断判断两个小数是否相等,只能判断它们之差的绝对值是不是在一个很小的范围,如小于0.0000001★★
26             cout << "无意义" << endl;
27             result = 0; //0的0次方没意义★★
28         } else {
29             result = 1;
30         }
31     } else {
32         if (equal(base, 0.0)) {
33             result = 0;
34         } else {
35             exponent = -exponent; //取绝对值
36             while (exponent > 0) {
37                 result = result * base;
38                 exponent--;
39             }
40             result = 1 / result;
41         }
42 
43     }
44     return result;
45 }
46 bool equal(double num1, double num2) { //判断两个小数是否相等★★
47     if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001)) {
48         return true;
49     } else {
50         return false;
51     }
52 }
53 /*
54  *这里没有使用此函数,此函数好处在于位运算的效率比乘除法及求余运算效率高
55  */
56 /*double PowerWithUnsignedExponent(double base, unsigned int exponent) {
57     if (exponent == 0) {
58         return 1;
59     }
60     if (exponent == 1) {
61         return base;
62     }
63     double result = PowerWithUnsignedExponent(base, exponent >> 1);//用右移代替除以2 ★
64     result *= result;
65     if ((exponent & 0x1) == 1) {//用与运算判断指数是奇数或偶数 ★
66         result *= base;
67     }
68     return result;
69 }*/
70 
71 int main() {
72     double result = Power(9, 5);
73     cout << result << endl;
74     return 0;
75 }

 

posted @ 2016-05-26 20:15  回看欧洲  阅读(163)  评论(0编辑  收藏  举报