如何使用 C# 中的遞迴查詢兩個數字的乘積?


首先,設定要相乘的兩個數字。

val1 = 10;
val2 = 20;

現在呼叫方法來查詢乘積。

product(val1, val2);

在乘積方法下,遞迴呼叫將為你獲取乘積。

val1 + product(val1, val2 – 1)

讓我們檢視完整程式碼,以使用遞迴查詢 2 個數字的乘積。

示例

using System;
class Calculation {
   public static void Main() {
      int val1, val2, res;
      // the two numbers
      val1 = 10;
      val2 = 20;
      // finding product
      Demo d = new Demo();
      res = d.product(val1, val2);
      Console.WriteLine("{0} x {1} = {2}", val1, val2, res);
      Console.ReadLine();
   }
}
class Demo {
   public int product(int val1, int val2) {
      if (val1 < val2) {
         return product(val2, val1);
      } else if (val2 != 0) {
         return (val1 + product(val1, val2 - 1));
      } else {
         return 0;
      }
   }
}

更新於: 2020 年 6 月 22 日

189 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.