在 C 中编写没有 math.h 的 Pow 函数 [英] Write Pow Function Without math.h in C

查看:47
本文介绍了在 C 中编写没有 math.h 的 Pow 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用 math.h 库的情况下为 pow 函数编写代码.

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

这段代码如何?当 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)
    }

推荐答案

一切似乎都很完美,除了一个条件:- when b<0.

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

对于b<0,直接返回

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

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)

这篇关于在 C 中编写没有 math.h 的 Pow 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆