使用遞迴查詢兩個數字乘積的 Python 程式


當需要使用遞迴技術查詢兩個數字的乘積時,使用一個簡單的 if 條件和遞迴。

遞迴計算較大問題的小部分輸出,並將這些部分組合起來以給出較大問題的解決方案。

示例

以下是相同內容的演示 -

 線上演示

def compute_product(val_1,val_2):
   if(val_1<val_2):
      return compute_product(val_2,val_1)
   elif(val_2!=0):
      return(val_1+compute_product(val_1,val_2-1))
   else:
      return 0
val_1 = int(input("Enter the first number... "))
val_2 = int(input("Enter the second number... "))
print("The computed product is: ")
print(compute_product(val_1,val_2))

輸出

Enter the first number... 112
Enter the second number... 3
The computed product is:
336

解釋

  • 定義了一個名為“compute_product”的方法,它將兩個數值作為引數。
  • 如果第一個值小於第二個值,則透過交換這些引數再次呼叫該函式。
  • 如果第二個值為 0,則透過傳遞第一個值並從第二個值中減去“1”並將其新增到函式的結果中來呼叫該函式。
  • 否則,該函式返回 0。
  • 在函式外部,使用者輸入兩個數字值。
  • 透過傳遞這兩個值來呼叫該方法。
  • 輸出顯示在控制檯上。

更新於: 2021年3月12日

536 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告