-
Recursive Help
How do i write a recursive function that takes two parameters with one representing the base of an exponent and the other the power of the exponent. For example if the function was called with the with the following parameters(5, 3) it would return 125
Thanks for your help
-
Ive gotten this so far but it doesnt work right. Maybe you might want to edit it.
Code:
#include <iostream>
#include <conio.h>
double exponent (double base, double power);
int main()
{
double b, p;
double answer;
cout << " Enter base and power respectively";
cin >>b,p;
cout << "result is "<<answer;
getch();
return 0;
}
double exponent(double b, double p)
{
double answer;
for (int power = 0; p<power; p--)
answer = b *p;
return answer;
}
-
Code:
#include <iostream>
#include <conio.h>
double exponent (double base, double power);
int main()
{
double b, p;
double answer;
cout << " Enter base and power respectively"<<endl;
cin >>b,p;
cout << "result is "<<answer;
getch();
return 0;
}
double exponent(double b, double p)
{
double answer;
answer = b * exponent(b,p-1);
return answer;
}
dont work either
-
Code:
##include <stdio.h>
#include <iostream.h>
int exponent (int, int);
void main()
{
int num;
int expo;
printf("Enter a number:");
scanf("%d", &num);
printf("Enter a exponent number:");
scanf("%lld", &expo);
printf("The answer is: %d\n", exponent(num, expo));
}
int exponent(int a, int b)
{
int sum=0;
int avg=1;
while (avg <b)
{
sum=sum*a;
avg++;
}
return sum;
}
This Code works 100% (it worked great for me)just make sure you just have to change the printf put cout<< and for scanf put cin>> dont forget that ok see yaa good lock
-
Oh yeah thats what i was missing. Hopefully Tommy will read this.
-
um your code dont work returns 0 as answer all the time.
Also i dont think its a recursive function. Even though i dont know why tommy would want to use one.
-
Code:
double power(double b, double p)
{
if (p > 1)
return b * power(b, --p);
return b;
}
-
-
Code:
i made some mastake in first one
#include <stdio.h>
#include <iostream.h>
int exponent (int, int);
void main()
{
int num;
int expo;
printf("Enter a number:");
scanf("%d", &num);
printf("Enter a exponent number:");
scanf("%lld", &expo);
printf("The answer is: %d\n", exponent(num, expo));
}
int exponent(int a, int b)
{
int avg=0;
int sum=1;
while (avg <b)
{
sum=sum*a;
avg++;
}
return sum;
}
//Now it's going to work look at the
//first one and see the diffrence ok look
//if you can find my mistake
gamer4life687 you can check to now if it works
-
Yet it's still not a recursive function.