辅助图
+ | - | 0 | |
+ | ~ | ~ | 1 |
- | ~ | ~ | 1 |
0 | 0 | x | 1 |
double PowerWithUnsignedExponet(double base, unsigned int absExponet) {
if (absExponet == 1)return base;
if (absExponet == 0) return 1;
double result = PowerWithUnsignedExponet(base, absExponet >> 1);
result *= result;
if (absExponet & 0x1 == 1) {
result *= base;
}
return base;
}
bool equal(double x, double y) {
if (x - y >= -0.0000001 && x - y <= 0.0000001)return true;
else return false;
}
double power(double base, int exponet) {
if (exponet == 0) return 1;
if (equal(base, 0.0) && exponet < 0) {
q_InvalidInput = -1;
return 0.0;
}
if (equal(base, 0.0) && exponet > 0) {
return 0;
}
//对指数求绝对值
unsigned int absExponet = (unsigned int)(exponet);
if (exponet < 0) {
absExponet = (unsigned int)(-exponet);
}
double result = PowerWithUnsignedExponet(base, absExponet);
if (exponet < 0)return 1.0 / result;
else return result;
}