C 幂函数负指数,无需 pow()

标签 c function exponent

我正在尝试制作一个用于学习目的的小型功率计算器,而不使用 pow, 但当指数为负数时它总是返回0.00,请帮忙。

完整代码:

#include<stdio.h>
//*  power caculator function

int power(x,y)
{
   float p=1.00;
   int i;
    if (y<0){
        y=-1*y;
        x=1/x;
    }
    for (i=1;i<=y;i++)
    {
        p=p*x;
    }

return p;
}



//*  main gets input, calls power caculator and prints result'
int main()
{
int b;
int e;
float p;
printf("enter base");
scanf("%d",&b);
printf("enter exponent");
scanf("%d",&e);
p=power(b,e);
printf("%d to the power of %d is %.2f",b,e,p);
return 0;
}
//* I am NOOB

最佳答案

您正在使用整数来保存十进制值,在本例中使用 x 和幂函数的返回类型。

尝试:

float power(x,y)
{
   float p=1.00;
   float xx = (float)x;
   int i;
    if (y<0){
        y=-1*y;
        xx=1/xx;
    }
    for (i=1;i<=y;i++)
    {
        p=p*xx;
    }

return p;
}

关于C 幂函数负指数,无需 pow(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49563188/

相关文章:

字符数组 - 为什么 for 循环不是无限的?

c - 为什么不返回修改函数参数值

java - java中的指数

matlab - 在 Matlab 中将 A^2 表示为 A * A

java - 如何处理这个格式化的数字 "XYe+02"

c - 强制编译时计算 C

c# - 使用 pinvoke 将结构数组中的嵌入式 C 结构数组传递给 C#

c++ - 是否可以将 macfuse 链接到 C++ 静态库?

ruby - 在 Ruby 中,为什么在使用 "do"和 "end"时不能将方法调用视为一个单元?

asp.net - 用于在按键时跳到文本框的 Jquery 函数