我正在尝试制作一个用于学习目的的小型功率计算器,而不使用 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/