2017-03-15 73 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(); 
} 

我固定的代码一点,做多一点可读。