How would you write this code using a recursive function?
#include <stdio.h>
double power(double a, int b);
int main()
{
double x, powr;
int n;
printf("Enter a number and the integer base and then the power\n");
while (scanf("%lf%d", &x, &n) == 2)
{
powr = power(x,n);
printf("%.3g to the power %d is %.5g\n", x, n, powr);
printf("Enter the next pair of numbers\n");
}
return 0;
}
double power(double a, int b)
{
double powr = 1;
int i;
if (b == 0)
{
if (a == 0)
printf("0 to the 0 undefined; using 1 as the value\n");
powr = 1.0;
}
else if (a == 0)
powr = 0.0;
else if (b > 0)
for(i = 1; i <= b; i++)
powr *= a;
else
powr = 1.0 / power(a, - b);
return powr;
}
wait so the recursive thing that you showed is that something you would replace with the original code so maybe look something like...
#include <stdio.h>
double power(double a, int b);
int main()
{
double x, powr;
int n;
printf("Enter a number and the integer base and then the power\n");
while (scanf("%lf%d", &x, &n) == 2)
{
powr = power(x,n);
printf("%.3g to the power %d is %.5g\n", x, n, powr);
printf("Enter the next pair of numbers\n");
}
return 0;
}
double power( double a, unsigned int b )
{
if( b == 0 )
{
if( a == 0 ) return 0 / 0.0 ;
else return 1 ;
}
else if( b == 1 ) return a ;
else return power( a, b/2 ) * power( a, (b+1)/2 );
}
double power_bf( double a, unsigned int b )
{
if( b == 0 )
{
if( a == 0 ) return 0 / 0.0 ;
else return 1 ;
}
#include <stdio.h>
double power(double a, unsignedint b); // *** unsigned int
int main()
{
double x ; // , powr;
unsignedint n; // *** unsigned int
puts( "Enter a number (base) and the non-negative integer exponent");
while( scanf("%lf%u", &x, &n) == 2 ) // %u for unsigned int
{
constdouble powr = power(x,n);
printf("%.3g to the power %u is %.5g\n", x, n, powr); // %u
printf("Enter the next pair of numbers\n");
}
return 0;
}
double power( double a, unsignedint b )
{
if( b == 0 )
{
if( a == 0 ) return 0 / 0.0 ;
elsereturn 1 ;
}
elseif( b == 1 ) return a ;
elsereturn power( a, b/2 ) * power( a, (b+1)/2 );
}
/*
double power_bf( double a, unsigned int b )
{
if( b == 0 )
{
if( a == 0 ) return 0 / 0.0 ;
else return 1 ;
}
else return a * power_bf( a, b-1 );
}
*/