Reputation: 1
I have written this program to give me the value of i
exposed to the power of j using recursion. As I am a student, practicing different methods of solving the same problem might be beneficial for me. The logic behind the code is working fine but when using negative power the function np()
returns 1.#QUAN0
instead of the actual value. I do not understand why this is happening.
PS: This code with negative power is working fine in my senior's laptop.
#include <stdio.h>
int pp(int i, int j, int m)
{
if(j==0)
return m;
else
{
m *= i;
pp(i,j-1,m);
}
}
float np(float i,int j,float m)
{
if(j==0)
return m;
else
{
m *= (1/i);
np(i,j+1,m);
}
}
int main()
{
int i;
int j;
printf("Enter the value of i=");
scanf("%d",&i);
printf("Enter the value of j=");
scanf("%d",&j);
if(j>=0)
printf("%d",pp(i,j,1));
else
printf("%f",np((float)i,j,(float)1));
return 0;
}
Upvotes: -2
Views: 73
Reputation: 3757
The problem is that in the pp
and np
only the branch where j=0 has a return statement.
You should add return
in the else branch as well:
for pp:
else{
m*=i;
return pp(i,j-1,m);
}
For np:
else{
m*=(1/i);
return np(i,j+1,m);
}
Upvotes: 3