Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java เพื่อแสดง Fibonacci Series


ในบทความนี้ เราจะเข้าใจวิธีการหาผลรวมคู่ของอนุกรมฟีโบนักชีจนถึงหมายเลข N อนุกรมฟีโบนักชีคือลำดับของตัวเลขที่เกิดจากผลรวมของจำนวนเต็มสองตัวก่อนหน้า อนุกรมฟีโบนักชีคู่คือจำนวนคู่ของอนุกรมฟีโบนักชี

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

อนุกรมฟีโบนักชีสร้างตัวเลขที่ตามมาด้วยการบวกตัวเลขก่อนหน้าสองตัว อนุกรมฟีโบนักชีเริ่มจากตัวเลขสองตัว - F0 &F1 ค่าเริ่มต้นของ F0 &F1 สามารถรับได้ 0, 1 หรือ 1, 1 ตามลำดับ

Fn = Fn-1 + Fn-2

ดังนั้น อนุกรมฟีโบนักชีจึงมีลักษณะเช่นนี้ −

F8 = 0 1 1 2 3 5 8 13

หรือนี่

F8 = 1 1 2 3 5 8 13 21

ป้อนข้อมูล

สมมติว่าข้อมูลที่เราป้อนคือ −

The input : 15

ผลผลิต

ผลลัพธ์ที่ต้องการจะเป็น −

The fibonacci series till 15 terms:

อัลกอริทึม

Step 1 - START
Step 2 - Declare values namely
Step 3 - Read the required values from the user/ define the values
Step 4 - Use a for loop to iterate through the integers from 1 to N and assign the sum of
consequent two numbers as the current Fibonacci number
Step 5- Display the result
Step 6- Stop

ตัวอย่างที่ 1

ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา โปรแกรม Java เพื่อแสดง Fibonacci Series .

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      int my_input , term_1, term_2, term_3;
      term_1 = 0;
      term_2 = 1;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      System.out.println("The fibonacci series till " + my_input + " terms:");
      for (int i = 1; i <= my_input; ++i) {
         System.out.print(term_1 + " ");
         term_3 = term_1 + term_2;
         term_1 = term_2;
         term_2 = term_3;
      }
   }
}

ผลลัพธ์

Required packages have been imported
A reader object has been defined
Enter the number : 15
The fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

ตัวอย่างที่ 2

ในที่นี้ มีการกำหนดจำนวนเต็มก่อนหน้านี้ และเข้าถึงและแสดงค่าบนคอนโซล

public class Main {
   public static void main(String[] args) {
      int my_input , term_1, term_2, term_3;
      my_input = 15;
      term_1 = 0;
      term_2 = 1;
      System.out.println("The number are defined as " +my_input );
      System.out.println("The fibonacci series till " + my_input + " terms:");
      for (int i = 1; i <= my_input; ++i) {
         System.out.print(term_1 + " ");
         term_3 = term_1 + term_2;
         term_1 = term_2;
         term_2 = term_3;
      }
   }
}

ผลลัพธ์

The number are defined as 15
The fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377