龙空技术网

数值的整数次方

ailx10 84

前言:

今天兄弟们对“c语言 10的几次方”大概比较关怀,小伙伴们都想要知道一些“c语言 10的几次方”的相关资讯。那么小编同时在网上收集了一些关于“c语言 10的几次方””的相关文章,希望我们能喜欢,同学们一起来学习一下吧!

数值的整数次方

数值是double类型,整数次方可能是负数0正数。

参考代码:

root@gt:/home/git/Code# ./a.out base:2.000000   exponent:10 res:1024.000000        exponent:-10    res=0.000977root@gt:/home/git/Code# cat pow.c #include <stdio.h>int g_invalidInput = 0;int equal(double base,double n){    int res = base - n;    if(res < 0)        res = -res;    if(res < 0.000001)        return 1;    else        return 0;}double PowerUnsigned(double base,unsigned int absExponent){    double res = 1.0;    while(absExponent)    {        res *= base;        --absExponent;    }    return res;}double Power(double base,int exponent){    if(equal(base,0.0) && exponent < 0)     {        g_invalidInput = 1;        printf("invalid input\n");        return 0.0;    }    unsigned int absExponent = (unsigned int)exponent;    if(exponent < 0)    {        absExponent = (unsigned int)(-exponent);    }    double res = PowerUnsigned(base,absExponent);    if(exponent < 0)    {        res = 1.0/res;    }    return res;}int main(){    double base = 2.0;    int exponent = 10;    double res0 = Power(base,exponent);    double res1 = Power(base,-exponent);    printf("base:%lf\texponent:%d\tres:%lf\n\t\texponent:%d\tres=%lf\n",base,exponent,res0,-exponent,res1);    return 0;}

扩展:

乘方算法可以优化:

double PowerUnsigned(double base,unsigned int absExponent){    double res = 1.0;    while(absExponent)    {        res *= base;        --absExponent;    }    return res;}

可以使用一点技巧,更快的计算乘方:

double PowerUnsigned(double base,unsigned int absExponent){    if(absExponent == 0)        return 1;    if(absExponent == 1)        retuen base;    double res = PowerUnsigned(base,absExponent >> 1);    res *= res;    if(absExponent & 0x1 == 1)        res *= base;//奇数    return res;}

标签: #c语言 10的几次方