Reputation: 565
class PowerRec
{
static double powRec(double x, int power)
{
if (power == 1){
return x;
}
return x * powRec(x, power - 1);
}
public static void main(String args[])
{
double x = 2;
System.out.println (x + " to the fourth is " + powRec (x, 4));
}
}
Upvotes: 0
Views: 167
Reputation: 36259
a³ = a * a ² = a * (a * a)
This is, what the code essentially does.
Now your new homework: Replace (x * y) with a call to mul (x, y), and solve the problem of multiplication with addition in the same habit.
Upvotes: 0
Reputation: 99
you have two returning statement in a row in your code. And wrong powRec method
static double powRec(double x, int power) {
if (power == 0) {
return 1;
}
return x * powRec(x, power - 1);
}
Upvotes: 1