计算java中的斐波纳契数

时间:2015-03-29 13:16:02

标签: java view model controller fibonacci

我正在尝试使用java中的模型视图控制器方法显示前20个fibbonacci数字。然而,我得到的输出只是最后一个数字(前19个没有显示),如果有人能够查看我的代码并指出哪里出错我会很棒:)

public class FibonacciModel {

public String fibModel(int a, int b, int c, int count){
    String result = "";
    //int c;
    while(count!=20)  // if you want first 100 fibonacci numbers then change 20 to 100 accordingly 
    {
        c=a+b;
        count++;
        result = c + " ";
        a=b;
        b=c;
    }
    return result;
}

}

public class FibonacciController {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int a = 1;
    int b = 1;
    int count = 2;
    int c = 0;



    FibonacciModel Model = new FibonacciModel();
    FibonacciView View = new FibonacciView();

    View.say(Model.fibModel(a, b, c, count));


}

}

public class FibonacciView {
    public < T > void say( T word ){
        System.out.print(word);
    }
}

3 个答案:

答案 0 :(得分:1)

您正在覆盖结果变量。试试result = result + c + " ";result += c + " ";

答案 1 :(得分:1)

检查一下:)

public static void getFibbonacci(int n){
        int total = 0;
        int prev = 1;        
        for (int x=1; x<n; x++){
            total = total + prev;
            prev = total - prev;

            System.out.println(total);
        }
    }

答案 2 :(得分:0)

public class fibbo {
public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    int a;
    System.out.println("Enter the number");
    a = sc.nextInt();
    int first = 0;
    int second = 1;
    int third;
    System.out.print("Fibbonacci series is= ");
    System.out.print("\t" + first + "\t" + second + "\t");
    for (int i = 0; i < a - 2; i++) {
        third = first + second;
        first = second;
        second = third;
        System.out.print(third + "\t");
    }

}