在此程序中,您將學習如何使用Java中的遞歸函數(shù)來計算數(shù)字的冪。
public class Power { public static void main(String[] args) { int base = 3, powerRaised = 4; int result = power(base, powerRaised); System.out.printf("%d^%d = %d", base, powerRaised, result); } public static int power(int base, int powerRaised) { if (powerRaised != 0) return (base * power(base, powerRaised - 1)); else return 1; } }
運行該程序時,輸出為:
3^4 = 81
在上面的程序中,您使用遞歸函數(shù)power()計算冪。
簡單地說,遞歸函數(shù)將底數(shù)與自身相乘,以獲得提升次數(shù),即:
3 * 3 * 3 * 3 = 81
Iteration | power() | powerRaised | result |
---|---|---|---|
1 | power(3, 4) | 4 | 3 * result2 |
2 | power(3, 3) | 3 | 3 * 3 * result3 |
3 | power(3, 2) | 2 | 3 * 3 * 3 * result4 |
4 | power(3, 1) | 1 | 3 * 3 * 3 * 3 * resultfinal |
Final | power(3, 0) | 0 | 3 * 3 * 3 * 3 * 1 = 81 |