老青菜

剑指offer-数值的整数次方

2017-01-22

题目

实现以下函数,求base的exponent次方。不得使用库函数。

double power(double base, int exponent)

分析

这个比较简单,公式如下:

n>0: y=x^n
n<0: y=1/x^n

实现

double power(double base, int exponent) {
    if (base-0.0<0.00000001 || base-0.0>-0.0000001) {
        //底数为0,无效
        return 0;
    }
    if (exponent == 0) {
        //指数为0,返回1
        return 1;
    }
    double result = 0.0;
    unsigned int absExponent = exponent;
    if (exponent<0) {
        absExponent = -exponent;
    }
    for (int i=0; i<absExponent; i++) {
        result *=result;
    }
    //如果为负数,结果是 1/a^b
    if (exponent<0) {
        result = 1.0/result;
    }
    return result;
}

添加测试代码

printf("%f,", power(-2, 0));
printf("%f,", power(0, 0));
printf("%f,", power(2, 0));
printf("\r\n");
printf("%f,", power(-2, 1));
printf("%f,", power(0, 1));
printf("%f,", power(2, 1));
printf("%f,", power(2, -1));
printf("\r\n");
printf("%f,", power(-2, 2));
printf("%f,", power(0, 2));
printf("%f,", power(2, 2));
printf("%f,", power(2, -2));

//output
1.000000,0.000000,1.000000,
-2.000000,0.000000,2.000000,0.500000,
4.000000,0.000000,4.000000,0.250000,
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章