Write Pow Function Without math.h in C [closed]

余生长醉 提交于 2021-01-29 07:06:05

问题


Hi I want to write a code for a pow function without using math.h libary.

How is this code?how can i fix it when b<0

    int MyPow(int a,int b){
      if(b<0)      
        return 1 / MyPow (a,-b)
      else if(b==0)
        return 1;
      else if(b==1)
        return a;
      else
        return a*MyPow(a,b-1)
    }

回答1:


Everything seems perfect except for one condition :- when b<0.

For b<0,simply return

return (1.0/a)*MyPow(a,abs(b)-1);   //where  abs(b) is  absolute value of b.

OR

return (1.0/a)*(MyPow(a,b+1));      

Also,your definition of function is not valid for performing negative exponentiation,you should change it to

float MyPow(int a,int b)



回答2:


Probably best way I think, found here

int pow(int base, int exp)
    {
      if(exp < 0)
        return -1;

        int result = 1;
        while (exp)
        {
            if (exp & 1)
                result *= base;
            exp >>= 1;
            base *= base;
        }

        return result;
    }



回答3:


A solution with less complexity taken from http://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/

float power(float x, int y)
{
    float temp;
    if( y == 0)
       return 1;
    temp = power(x, y/2);       
    if (y%2 == 0)
        return temp*temp;
    else
    {
        if(y > 0)
            return x*temp*temp;
        else
            return (temp*temp)/x;
    }
}


来源:https://stackoverflow.com/questions/25525536/write-pow-function-without-math-h-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!