2017-03-15 3 views
1

숙제에 어려움이 있습니다 ... "사용자에게 두 가지 숫자를 알려주는 프로그램을 작성하십시오 : Lower와 Upper 프로그램은 피보나치 숫자를 모두 아래에서 위로 인쇄해야합니다 그리고 피보나치 시리즈의 모든 짝수의 합. " 두 입력 사이에 숫자를 얻는 방법을 모르겠습니다. 이제는 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()); 

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

읽을 수있는.

관련 문제