2017-03-15 5 views
1

私は宿題に問題があります... "下位と上位の2つの数字をユーザーに尋ねるプログラムを書いてくださいプログラムはフィボナッチ数を下から上のフィボナッチ級数のすべての偶数の和となります。私は2つの入力の間に数字を得る方法を知らない。今はゼロから数えて...?ここで 2つの入力間のフィボナッチ数

は、私がこれまで持っているものです。

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(); 
} 

読める。

関連する問題