实数的整数次方(考虑了优化效率做法)
//添加全局变量以便考虑次方是否出错 bool InvaildInput = false; //判断数值是否相等,实数需要相关判断。。。 bool EqualD(const double& num1, const double& num2) { return fabs(num1 - num2) > 1E-6 ? false : true; } //求取实数的正次方 double PowerD_UINT(const double& base, unsigned int exponent) { //普通做法 //double res = 1.0; //for (size_t i = 0; i < exponent; i++) //{ // res *= base; //} //递归的 if (0 == exponent) return 1.0; if (1 == exponent) return base; double res = PowerD_UINT(base, exponent >> 1); res *= res; //求平方 if (1 == exponent & 0x01) //判断exponent是否为偶数 res *= base; return base; } //求取实数的整数次方 double PowerD(double base, int exponent) { InvaildInput = false; //0的正次方以及负次方都定义为0.0 if (EqualD(base, 0)) { if (exponent < 0) { InvaildInput = false; return 0.0; } else { return 0.0; } } if (0 == exponent) { return 1.0; } if (EqualD(base,1.0)) { return 1.0; } //0次方在初始位置已经解决 double res = 0.0; unsigned uint_exponent; if (exponent<0) { //注意不能直接unsigned int(exponent) //unsigned short(-1)=65535... uint_exponent = unsigned int(-exponent); res = PowerD_UINT(base, uint_exponent); res = 1.0 / res; } else { uint_exponent = unsigned int(exponent); res = PowerD_UINT(base, uint_exponent); res = 1.0 / res; } return res; }
最后的递归简直不能再赞了,学到了!
这里针对整数》1的递归次数应该在合理的范围内,不会造成栈溢出。
unsigned int x = UINT_MAX,n=0; for (x; x >= 1; x = x >> 1) { cout << ++n << endl; }
结果为32次!