2017-03-15 68 views
1

我的家庭作業有困難......「寫一個程序會詢問用戶兩個數字:Lower和Upper,你的程序應該打印所有的Fibonacci數字,範圍從低到高以及斐波那契數列中所有偶數的總和。「我不知道如何獲得兩個輸入之間的數字。現在它只給出從零到......的數字?兩個輸入之間的斐波那契數字

這是我到目前爲止有:

public static void main(String[] args) 
{ 
    Scanner scr = new Scanner(System.in); 
    System.out.println ("Enter lower bound:"); 
    int lower = Integer.parseInt(scr.nextLine()); 
    System.out.println ("Enter upper bound:"); 
    int upper = Integer.parseInt(scr.nextLine()); 

    int fiboCounter = 1; 
    int first = 0; 
    int second = 1; 
    int fibo = 0; 
    int oddTotal = 1; 
    System.out.println("The fibonacci numbers between "); 
    while(fiboCounter < upper) 
    { 
     fibo= first + second; 
     first = second; 
     second = fibo; 
     if(fibo % 2 == 0) 
      oddTotal = oddTotal + fibo; 

     System.out.print(" "+ fibo+ " "); 
     fiboCounter++; 
    } 
    System.out.println(); 
    System.out.println("Total of even Fibos: "+ oddTotal); 
} 
+2

首先,像往常一樣計算斐波納契數,當超過上限(使用循環)時停止。在循環內部,除了計算斐波納契數字外,如果它大於下限,則只打印出來。 – DVT

回答

0

你可以簡單地檢查計算出的數量是否足夠大:

public static void main(String[] args) { 
    Scanner scr = new Scanner(System.in); 
    System.out.println ("Enter lower bound:"); 
    int lower = Integer.parseInt(scr.nextLine()); 
    System.out.println ("Enter upper bound:"); 
    int upper = Integer.parseInt(scr.nextLine()); 

    // This is how you can initialize multiple variables of the same type with the same value. 
    int fiboCounter, second, oddTotal = 1; 
    int first, fibo = 0; 

    System.out.println("The fibonacci numbers between "); 
    while(fiboCounter < upper) { 
     fibo= first + second; 
     first= second; 
     second=fibo; 
     if(fibo%2==0) oddTotal=oddTotal+fibo; 

     // Just check if its high enough 
     if(fibo > lower) { 
      System.out.print(" "+ fibo + " "); 
     } 
     fiboCounter++; 
    } 

    System.out.println("\nTotal of even Fibos: "+ oddTotal); 
    // The \n is just the same as System.out.println() 

    // You probably want to close the scanner afterwards 
    scanner.close(); 
} 

我固定的代碼一點,做多一點可讀。