เมื่อต้องการหาลำดับฟีโบนัชชีโดยไม่ใช้ Recursion ให้รับ input จากผู้ใช้ และใช้ลูป '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
คำอธิบาย
- รับ input ตัวเลขแรกและตัวเลขที่สองจากผู้ใช้
- รับจำนวนพจน์จากผู้ใช้
- พิมพ์ตัวเลขแรกและที่สองบนคอนโซล
- เริ่มลูป while และทำดังนี้:
- บวกตัวเลขแรกและที่สอง กำหนดให้ตัวเลขที่สาม
- กำหนดตัวเลขที่สองให้ตัวเลขที่สาม
- กำหนดตัวเลขที่สามให้ตัวเลขที่สอง
- พิมพ์ตัวเลขที่สามบนคอนโซล
- ลดจำนวนพจน์ลง 1