使用 Java 中的遞迴將 x 提升到 n 次方


可以使用遞迴計算一個數的冪。這裡,x 為數,它被提升到 n 次方。

演示這一點的程式如下

示例

 演示

public class Demo {
   static double pow(double x, int n) {
      if (n != 0)
         return (x * pow(x, n - 1));
      else
         return 1;
   }
   public static void main(String[] args) {
      System.out.println("7 to the power 3 is " + pow(7, 3));
      System.out.println("4 to the power 1 is " + pow(4, 1));
      System.out.println("9 to the power 0 is " + pow(9, 0));
   }
}

輸出

7 to the power 3 is 343.0
4 to the power 1 is 4.0
9 to the power 0 is 1.0

現在讓我們瞭解一下上述程式。

pow() 方法計算 x 提升到 n 次方。如果 n 不為 0,它會遞迴呼叫自身並返回 x * pow(x, n - 1)。如果 n 為 0,它返回 1。下面是一個演示此過程的程式碼段

static double pow(double x, int n) {
   if (n != 0)
      return (x * pow(x, n - 1));
   else
      return 1;
}

在 main() 中,使用不同的值呼叫 pow() 方法。下面是一個演示此過程的程式碼段

public static void main(String[] args) {
   System.out.println("7 to the power 3 is " + pow(7, 3));
   System.out.println("4 to the power 1 is " + pow(4, 1));
   System.out.println("9 to the power 0 is " + pow(9, 0));
}

更新於: 30-Jul-2019

654 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告