题目链接:http://ac.jobdu.com/problem.php?pid=1514
分析:求一个double类型数的整数次方。考虑到以下情况:
1. 底数为0,指数为非负数,此时结果为0;
2. 底数为0,指数为负数,此时为非法情形;
3. 指数为负数时,可转换为整数,最后再求倒数。
tip:注意double类型的判断为0的方法,不能简单的用等于0.0!如果两个小数的差的绝对值很小,如小于0.0000001,就可以认为它们相等。
C++实现:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
bool equal(double a, double b)//判断double类型的数是否为0.
{
if((a - b > -0.0000001) && (a - b) < 0.0000001)
return true;
return false;
}
double process(double a, unsigned int e)//递归的方法求
{
if(e == 0)
return 1;
if(e == 1)
return a;
double res = process(a, e >> 1);
res *= res;
if(e & 1 == 1) //奇数
res *= a;
return res;
}
void input()
{
int t;
double zero = 0.0;
double base;
int exp;
scanf("%d",&t);
while(t-- > 0)
{
scanf("%lf%d",&base,&exp);
if(equal(base,0.0) && exp >= 0)
{
printf("%.2ef\n", zero);
}
else if(equal(base, 0.0) && exp < 0)
{
printf("INF\n");
}
else
{
unsigned int absexp = (unsigned int)(exp);
if(exp < 0)
absexp = (unsigned int)(-exp);
double res = process(base, absexp);
if(exp < 0)
res = 1.0 / res;
printf("%.2ef\n", res);
}
}
}
int main()
{
input();
return 0;
}