给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
// test14.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<cstring>
//#include<stdexcept>
#include<exception>
using namespace std;
class Solution {
public:
double Power(double base, int exponent) {
if (base == 0&&exponent<=0)//base为负,指针也为负
{
cout << "无效的输入"<<endl;
return 0;
}
double flag = 1;
if (exponent > 0)//指数为正
{
for (int i = 0; i < exponent; i++)
flag *= base;
}
else if (exponent < 0)//指数为负
{
for (int i = 0; i < -exponent; i++)
flag *= (1/base);
}
else { //指数为0
return flag;
}
return flag;
}
};
int main()
{
Solution so;
double base;
int exponent;
while (true)
{
cout << "请输入一个浮点数: ";
cin >> base;
cout << "请输入一个整数: ";
cin >> exponent;
cout << base<<"的"<<exponent<<"次方是"<< so.Power(base,exponent)<< endl;
cout << endl;
}
}