何海涛面试题11,数值的整数次方
不使用库函数,实现double power(double base,int ex)。
#include<iostream> using namespace std; bool invalidinput=false; //判断两浮点数数是否相等的方法,不能直接用等号 bool equal(double num1,double num2) { if((num1-num2>-0.0000001)&&(num1-num2<0.00000001)) { return true; } else return false; } //采用递归算法,O(logn) double power_unsigned_ex(double base,int ex) { if(ex==0) return 0; if(ex==1) return base; double result=power_unsigned_ex(base,ex>>1);//采用移位运算,效率更高 result *=result; if(ex & 0x1 ==1)//判断指数是不是奇数 result*=base; return result; } double power(double base,int ex) { invalidinput=false; if(equal(base,0.0)&&ex<0)//注意0.0的负数次方 { invalidinput=true; return 0.0; } unsigned int absEx=(unsigned int)(ex); if(ex<0) { absEx=(unsigned int)(-ex); } double result=power_unsigned_ex(base,absEx); if(ex<0) return 1.0/result; return result; } int main() { double x; int y; while(cin>>x>>y) cout<<power(x,y)<<endl; return 0; }