1.题目描述:
实现函数double Power(double base,int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
2.源代码:
// Copyright (c) 2015年 skewrain. All rights reserved.
#include <iostream>
#include <stdio.h>
using namespace std;
//自以为题目简单的解法,不能处理负数和0。
double Power1(double base,int exponent)
{
double result = 1.0;
for (int i=1; i<=exponent; i++) {
result *= base;
}
return result;
}
//全面但不够高效的解法,使用全局变量。
bool g_InvalidInput = false;
bool equal(double num1,double num2)
{
if((num1-num2 >-0.0000001)&&(num1-num2 <0.0000001))
return true;
else
return false;
}
double PowerWithUnsignedExponent1(double base,unsigned int exponent)
{
double result = 1.0;
for (int i=1; i<=exponent; i++) {
result *= base;
}
return result;
}
double Power2(double base,int exponent)
{
g_InvalidInput = false;
if(equal(base, 0.0) && exponent <0)
{
g_InvalidInput = true;
return 0.0;
}
unsigned int absExponent = (unsigned int)exponent;
if (exponent < 0) {
absExponent = (unsigned int)(-exponent);
}
double result = PowerWithUnsignedExponent1(base,absExponent);
if (exponent < 0) {
result = 1.0/result;
}
return result;
}
//全面而高效的解法
double PowerWithUnsignedExponent2(double base,unsigned int exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
//用右移运算符代替了除以2
double result = PowerWithUnsignedExponent2(base,exponent>>1);
result *= result;
//用位与运算符代替了求余运算符(%)来判断一个数是奇数还是偶数。
if((exponent & 0x1) == 1)
result *= base;
return result;
}
int main(int argc,char *argv[]){
int base,exponent;
cout<<"请输入基数:";
cin>>base;
cout<<"请输入指数:";
cin>>exponent;
cout<<base<<"的"<<exponent<<"次方的值为:"<<Power1(base,exponent)<<endl;
cout<<base<<"的"<<exponent<<"次方的值为:"<<Power2(base,exponent)<<endl;
return 0;
}