2016-08-19 67 views
0

我有一個關於在Java中生成斐波那契數字的初學者問題。打印字符串而不是斐波納契數字

在該java程序,該方法應打印Fibonnacci數字序列從BeginIndexLastIndex,所以它應該打印"Hi"(而不是數)如果該數目是5的倍數,打印"I am"如果數目是7的倍數如果數字是35的倍數,則打印"Hi I am me"。我不確定如何執行此操作。

class FibonacciClass { 
    public static void main(String args[]) throws Exception { 

     generatefibonacci(10, 20); 
     generatefibonacci(0, 1); 


    } 


     private static void generatefibonacci(int BeginIndex, int LastIndex) { 



     } 

回答

1

另一種可能性:

private static void generateFibonacci(int beginIndex, int lastIndex) { 

    int len = lastIndex + 1; 
    int[] fib = new int[len]; 
    fib[0] = 0; 
    fib[1] = 1; 

    // Building Fibonacci sequence from beginIndex through lastIndex 
    for (int i = 2; i < len; ++i) 
     fib[i] = fib[i-1] + fib[i-2]; 

    // Printing 
    for (int index = beginIndex; index <= lastIndex; ++index) { 

     if ((fib[index] % 5 == 0) && (fib[index] % 7 == 0)) { 
      System.out.println("Hi I am me"); 
     } 
     else if (fib[index] % 5 == 0) { 
      System.out.println("Hi"); 
     } 
     else if (fib[index] % 7 == 0) { 
      System.out.println("I am"); 
     } 
     else { 
      System.out.println(fib[index]); 
     } 
    } 
} 
+0

我認爲你應該測試'如果(FIB [指數]%5 == 0)',而不是如果該索引。你也可以測試第一種情況'if(fib [index]%35 == 0)'而不是測試7和5,但這只是一個小的優化。 – Orin

+0

是的,我會改正你的帖子。我想他想知道斐波納契數是否可以被5或7整除,而不是索引可以被5或7整除。這是我的假設,否則你的答案看起來不錯。 – Orin

+0

代碼更正! – tnas

0

您正在尋找的是模數運算符,%。它將通過其操作數返回除法的其餘部分。因此,從if(x%5 == 0 & x%7 == 0)接收真值將表示數字x是5和7的倍數。如果此情況未通過,則應使用else if語句單獨檢查x是否是5的倍數,然後是另一個用於if x是7的倍數,每個分支調用System.out.println(「x是y的倍數」);

0

每次generatefibonacci產生了一個結果,你必須檢查模(%)。

像這樣:

private static generatefibonnacci(int startIndex, int endIndex){ 
int result = -1; 
//do generating stuff 
//and set "result" to generated fibonacci 
//and then 
if(result%5==0){ 
    System.out.println("Hi"); 
} else if(result%7==0){ 
    System.out.println("Hi I am me!"); 
} //and so on 

所以這只是一個小例子。 玩得開心

0
private static void generatefibonacci(int BeginIndex, int LastIndex) { 
    int[] numbers = new int[LastIndex + 2]; //creates an array to put fibonacci numbers in 
    numbers[0] = 1; numbers[1] = 1; 
    for(int i = 2; i <= LastIndex; i ++){ 
     numbers[i] = numbers[i - 1] + numbers[i - 2]; //generates the Fibonacci Sequence 
    } 
    for(int i = BeginIndex; i <= LastIndex; i ++){ 
     if(numbers[i] % 5 == 0 && numbers[i] % 7 == 0){//if the remainder when the numbers/5 equals 0 and the remainder when the numbers/7 equals 0 
      System.out.println("Hello I am me"); 
     } 
     else if(numbers[i] % 5 == 0){ //if the remainder when the numbers/5 equals 0 
      System.out.println("I am"); 
     } 
     else if(numbers[i] % 7 == 0){ //if the remainder when the numbers/7 equals 0 
      System.out.println("Hi"); 
     } 
     else{ //if none of the above three conditions are true 
      System.out.println(numbers[i]); 
     } 
    } 

}