【问题标题】:calculating fibonacci numbers in java在java中计算斐波那契数
【发布时间】:2015-03-29 13:16:01
【问题描述】:

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

公共类 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;
}

}

公共类 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);
    }
}

【问题讨论】:

  • 是时候做一些调试了,不是吗?

标签: java view model controller fibonacci


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    看看这个:)

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

    【讨论】:

      【解决方案3】:
      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");
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2013-03-31
        • 1970-01-01
        • 2016-12-11
        • 2020-01-18
        • 2012-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-02
        相关资源
        最近更新 更多