不使用遞迴的 Python 程式來求斐波那契數列


當需要求斐波那契數列而不使用遞迴技術時,會從使用者接收輸入,然後使用“while”迴圈獲取序列中的數字。

示例

以下是相同的說明演示——

 動態演示

first_num = int(input("Enter the first number of the fibonacci series... "))
second_num = int(input("Enter the second number of the fibonacci series... "))
num_of_terms = int(input("Enter the number of terms... "))
print(first_num,second_num)
print("The numbers in fibonacci series are : ")
while(num_of_terms-2):
   third_num = first_num + second_num
   first_num=second_num
   second_num=third_num
   print(third_num)
   num_of_terms=num_of_terms-1

輸出

Enter the first number of the fibonacci series... 2
Enter the second number of the fibonacci series... 8
Enter the number of terms... 8
2 8
The numbers in fibonacci series are :
10
18
28
46
74
120

說明

  • 從使用者接收第一個數字和第二個數字輸入。
  • 還需要從使用者接收項數。
  • 在控制檯上列印第一個和第二個數字。
  • while 迴圈開始,然後進行如下操作——
  • 將第一個和第二個數字相加並賦給第三個數字。
  • 將第二個數字賦給第三個數字。
  • 將第三個數字賦給第二個數字。
  • 在控制檯上列印第三個數字。
  • 項數減 1。

更新於: 12-Mar-2021

5K+ 次瀏覽

Kickstart Your Career

透過完成課程獲得認證

Get Started
廣告
© . All rights reserved.