-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
56 lines (41 loc) · 832 Bytes
/
Copy pathmain.cpp
File metadata and controls
56 lines (41 loc) · 832 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 计算一个数的n次方,不使用库函数
#include <iostream>
#define PRECISION 0.000001
bool Equal(double lhs, double rhs)
{
bool ret = false;
if ((lhs - rhs > -PRECISION) && (lhs - rhs < PRECISION))
ret = true;
return ret;
}
double PowerWithUnsignedExpon(double base, int absExponent)
{
if (absExponent == 0)
return 1;
if (absExponent == 1)
return base;
double res = PowerWithUnsignedExpon(base, absExponent >> 1);
res *= res;
if (absExponent & 1)
res *= base;
return res;
}
double Power(double base, int exponent)
{
if (Equal(base, 0.0))
{
return 0.0;
}
unsigned int absExponent = (unsigned)exponent;
if (exponent < 0)
absExponent = (-exponent);
double res = PowerWithUnsignedExpon(base, absExponent);
if (exponent < 0)
res = 1.0 / res;
return res;
}
int main()
{
Power(2, -3);
return 0;
}