C Power function negative exponent without pow()
16,117
You are using integers to hold decimal values, in this case with x and with the return type of the power function.
try:
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;
}
Related videos on Youtube
Author by
NOOBAF
Updated on June 04, 2022Comments
-
NOOBAF almost 2 years
I'm trying to make a little power calculator for learning purposes in C without using pow, but it always returns 0.00 when exponent is negative, please help.
full code:
#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
-
Weather Vane about 6 years
int power(x,y)
what are the argument types? Also please pay attention to compiler warnings. By omitting the type, then compiler assumes they areint
. You did supplyint
arguments butx=1/x;
assumes integer division. -
Christian Gibbons about 6 yearsWhat is
1/x
for anyx > 1
? -
Lee Daniel Crocker about 6 yearspow() works just fine with negative exponents, but then you chop them off by declaring your function to return int.
-
infinite about 6 yearsTruncation is a problem apart from the other basic ones. 1 divided by any int is 0.
-
Weather Vane about 6 yearsThe return value of
power()
isint
. So even when you get the argument types (or the casting) right, any negative power (result < 1) will return0
. -
Christian Gibbons about 6 years@infinite almost, but not quite.
1
and-1
will give you a different result. And0
makes babies cry. -
infinite about 6 years@ChristianGibbons I tried 1/i, 1/(-i), -1/(i), -1/(-i) where i is an integer other than 0 and got the same result 0 on gcc 6.3
-
Christian Gibbons about 6 years@infinite
1
is an integer other than 0. I would be very interested in a system where1/1
comes out to0
.
-
-
NOOBAF about 6 yearsAh I SEE NOW! Thanks Miguel!
-
Miguel Mota about 6 yearsGreat! Best regards!
-
Christian Gibbons about 6 yearsNot the downvoter, but I assume it's because the function still has not explicitly defined the types of
x
andy
. -
Miguel Mota about 6 yearsyea... defining types for parameters will help a lot... I agree.. I'll down vote myself... jejeje