没有 pow() 的 C 幂函数负指数

C Power function negative exponent without pow()

我正在尝试在不使用 pow 的情况下制作一个用于 C 语言学习目的的小功率计算器, 但它总是 returns 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 和 return 类型的幂函数。

尝试:

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;
}

明确定义 x 和 y 的数据类型,然后调整 return 数据类型。