My website shares decoration Cases
To put it bluntly, you can call yourself until the method body does not conform to the conditions.
All the methods you have seen so far can call other methods. However, a method can also call itself. We call this call as a recursion. Obviously. You must include some logical judgments in the recursive method so that you can stop calling itself at the end. We will use a simple example to introduce its implementation process. We can write a method to calculate the integer power of a variable, that is, to calculate the Npower of x or x *... * X, that is, x is multiplied by its own n times. We can apply this formula to obtain the result, that is, the Npower of x is equal to the (n-1) Power of x multiplied by x.
Here is a complete program containing the recursive method power:
Public class PowerCalc
{
Public static void main (string [] arga)
{
Double x = 5.0
System. out. println (x + to the power 4 is + power (x, 4 );
System. out. println (7.5 to the power 5 is # power (7.5, 5 ));
System. out. println (7.5 to the power 0 is # power (7.5, 0 ));
System. out. println (10 to the power-2 is # power (10,-2 ));
)
// Raise x to the power n
Static double power (double x, int n)
{
It (n> 1)
Return x * power (x, n = 1); // Recersive call
Else if (n <0)
Return 1.0/power (x, n); // Negative Dower of x
Else
Return n = 0? 1.0: x; // when n is return 1. otherwise x
}
}
The output result of this program is:
5.0 to the power 4 is 625.0
7.5 to the power 5 is 23730.46875
7.5 to the power 0is 1.0
10 to the power-2 is 0.01