Reputation: 1536
I have a function that calculate the power of a double number, and the next task was to add the option so it could deal with negative power.
So I added this code to the function:
if (p < 0)
{
for (y = 1; y <= p; y++)
{
pow *= n;
}
pow = 1/pow;
}
The whole program is short so I will share it too:
#include <stdio.h>
double power(double n, int p); // ANSI prototype
int main(void)
{
double x, xpow;
signed int exp;
printf("Enter a number and the positive integer power");
printf(" to which\nthe number will be raised. Enter q");
printf(" to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2)
{
xpow = power(x,exp); // function call
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");
return 0;
}
double power(double n, signed int p) // function definition
{
double pow = 1;
int i;
int y;
if (p < 0)
{
for (y = 1; y <= p; y++)
{
pow *= n;
}
pow = 1/pow;
}
for (i = 1; i <= p; i++)
pow *= n;
return pow; // return the value of pow
}
If im entering the input 5.0
and the power -3
i suppose to get 0.008
, and im getting 1
...
Upvotes: 0
Views: 323
Reputation: 48587
If you're entering your power as -3, none of your for conditions will be true.
if (p < 0)
{
for (y = 1; y <= p; y++)
{
pow *= n;
}
pow = 1/pow;
}
If p < 0, y will never be less than p.
Upvotes: 0
Reputation: 3571
Did you forget an else ? for the if
if (p < 0)
{
for (y = 1; y <= -p; y++)
{
pow *= n;
}
pow = 1/pow;
}
else
for (i = 1; i <= p; i++)
pow *= n;
Upvotes: 1