2013-04-09 159 views
0

這個程序應該從用戶那裏得到一個斐波那契數,程序會計算它是什麼,同時確保用戶輸入一個正數和一個不小於斐波那契數70的數。所以,如果用戶輸入7,它應該打印13.方法fibcalc()應該進行計算。 當我嘗試和編譯程序,我得到的錯誤「的方法fibcalc類斐波納契不能應用於給定類型:System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3));和‘無法找到符號’return x3;這裏是我的代碼:斐波那契計算

import java.util.Scanner; 

public class Fibonacci 
{ 
    public static void main (String args[]) 
    { 
    Scanner input = new Scanner (System.in); 

     int num; 
     double x3 = 0; 


      System.out.print("Which Fibonacci number would you like? "); 
     num = input.nextInt(); 
      do 
     { 
     System.out.print("Which Fibonacci number would you like? "); 
     num = input.nextInt(); 
    }while(num >= 0 && num <= 70); 

    System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3)); 

} 


public static double fibcalc(int num) 
{ 
    int x1 = 0; 
    int x2 = 1; 

     if (num == 0) 

      return 0; 

     else if (num == 1) 

      return 1; 

     else 

      for (int x3 = 0; x3 < num; x3++) 
       { 
        x3 = x1 + x2; 
        x1 = x2; 
        x2 = x3; 
       } 
       return x3; 

} 
    } 

可能有其他的問題我已經錯過了。我很新到Java。在此先感謝。

+2

X3不外存在循環 – 2013-04-09 03:33:39

+0

所以不是環路我會以外它聲明中聲明X3的? – user1858350 2013-04-09 03:36:18

+0

是的,宣佈它在固定的錯誤之外。 – user1858350 2013-04-09 03:39:14

回答

2

fibcalc()方法有一個int參數,但你與參數調用它。

變化從

fibcalc(num, x3) 

fibcalc(num) 

即調用更改行:

System.out.printf("Fibonacci #%d is %f", num, fibcalc(num)); 

另外,如果你想準確的數字你的結果,使用double到變化使用BigInteger,可以準確地處理任意大的數字。

+0

擺脫了與此相關的錯誤。 – user1858350 2013-04-09 03:49:26

0

如果要計算斐波那契數,你可以使用直接(非遞歸,非迭代)formula for Fibonacci numbers

Fib(n) = (pow((1+sqrt(5))/2, n) + pow((1-sqrt(5))/2, n))/sqrt(5) 

事實證明,所有n >= 0,可以簡化這個公式:

Fib(n) = round(pow((1+sqrt(5))/2, n)/sqrt(5)) 

知道了這一點,你可以用下面這個簡單的實施fibcalc

public static double fibcalc(int num) { 
    return Math.floor(Math.pow((1+Math.sqrt(5))/2, num)/Math.sqrt(5) + 0.5); 
} 
+0

我試圖實現這一點,並得到了錯誤「可能的精度要求詮釋寬鬆發現:長我是否應該改變公共靜態詮釋爲公共靜態長? – user1858350 2013-04-09 04:07:05

+0

這是奇怪的在我的例子中沒有'長'的任何地方。在[IdeOne.com](http://ideone.com/emxMKV)看這個工作示例。它編譯時沒有警告並且工作正常 – mvp 2013-04-09 04:17:52

+0

我不知道我是否正確使用它,它給了我一個奇怪的答案如果我輸入70以上的東西,它不應該這樣做 – user1858350 2013-04-09 04:33:38

0

您也可以使用下面的計算器來計算(使用Javascript)斐波那契序列:enter link description here

+0

你好,在提供另一篇文章的鏈接是有益的,答案應該包含解決方案,請添加更多的細節。 – Chaithanya 2017-03-16 23:01:17