剑指offer12:数值的整数次方
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
解法一:分类讨论
class Solution {
public:
double Power(double base, int exponent) {
double answer = 1.0;
if (exponent == 0)
return 1.0;
else if (base == 0.0)
return 0.0;
else if (exponent>0)
{
for (int i = 1; i <= exponent; i++)
{
answer *= base;
}
}
else
{
base = 1 / base;
for (int i = 1; i <= (0 - exponent); i++)
{
answer *= base;
}
}
return answer;
}
};
解法二:调用pow库函数
class Solution2 {
public:
double Power(double base, int exponent) {
return pow(base, exponent);
}
};
main函数
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
double base;
cout << "请输入浮点数base: " << endl;
cin >> base;
int exponent;
cout << "请输入次幂:" << endl;
cin >> exponent;
Solution2 answer;
cout << "答案是:" << answer.Power(base, exponent)<<endl;
system("pause");
return 0;
}