数值的整数次方
2016-02-14 23:33
225 查看
计算的时候,如果指数是负数,则先计算他的正数,然后求结果,再最后求这个结果的倒数,就是最终答案
考虑一个特殊情况,那就是如果底数是0,指数是负数,这样按照上面办法的话,最后一步,分母会变成0,这样是非法的
代码如下
考虑一个特殊情况,那就是如果底数是0,指数是负数,这样按照上面办法的话,最后一步,分母会变成0,这样是非法的
代码如下
#include <iostream> using namespace std; bool gInvalid=false; double PowWithUnsignedExponent(double base,unsigned int exponent) { double result=1.0; for(int i=1;i<=exponent;i++) { result*=base; } return result; } bool equal(double a,double b) { if((a-b)>-0.00001&&(a-b)<0.00001) return true; return false; } double Pow(double base,double exponent) { gInvalid=false; //如果底数是0 指数是负数 那就应该返回错误 if(equal(base,0.0)&&exponent<0) { gInvalid=true; cout<<"the base and exponet are less than 0,illegle parameter!"; exit(1); } unsigned int absExponent=(unsigned int)exponent; if(exponent<0) absExponent=(unsigned int)(-exponent); double ret=PowWithUnsignedExponent(base,absExponent); if(exponent<0) ret=1.0/ret; return ret; } int main() { cout<<Pow(0,-2)<<endl; return 0; }
相关文章推荐
- JavaScript的单元测试
- post 发送xml
- 小雷郑重承诺:在2017年之前,对大学毕业4年以来的所有努力和探索,做一个全面客观的总结,技术研究、工作创业、投资理财、朋友感情等
- 小雷郑重承诺:在2017年之前,对大学毕业4年以来的所有努力和探索,做一个全面客观的总结,技术研究、工作创业、投资理财、朋友感情等
- 【SPOJ-PRIME1】Prime Generator【区间质数筛】
- 自己实现下载框架(二)
- redis编译安装:make 的新错误--collect2: ld returned 1 exit status
- 小雷郑重承诺:在2017年之前,对大学毕业4年以来的所有努力和探索,做一个全面客观的总结,技术研究、工作创业、投资理财、朋友感情等
- 人员信息管理
- fastjson对Date的处理
- android 批量上传图片
- linux xargs详解
- Chapter1 基本Web应用程序
- VMWare下安装ubuntu64位出现错误“kernel requires an x86_64 cpu, but only detected ”
- 蓝桥杯——最小乘积(基本型)
- [Python]Threading.Thread之Daemon线程
- 【CodeForces 504A】Misha and Forest
- iPhone修改时间变砖
- iPhone修改时间变砖
- CSU 1556 Pseudoprime numbers