问题
This program is supposed to get a Fibonacci number from the user and the program will calculate what it is while making sure that the user entered a positive number and a number no less than the Fibonacci number 70. So, if the user entered 7, it should print 13. The method fibcalc() is supposed to do the calculations.
When I try and compile the program, I get the errors "method fibcalc in class Fibonacci cannot be applied to given types: System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3));
and "cannot find symbol" return x3;
Here's my code:
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;
}
}
There are probably other problems I've missed. I'm pretty new to java. Thanks in advance.
回答1:
The fibcalc()
method has a single int
parameter, but you are calling it with two parameters.
Change the call from
fibcalc(num, x3)
to
fibcalc(num)
ie change that line to:
System.out.printf("Fibonacci #%d is %f", num, fibcalc(num));
Also, if you want accurate numbers for your results, change from using double
to using BigInteger, which can handle arbitrarily large numbers accurately.
回答2:
If you want to compute Fibonacci numbers, you can use direct (non-recursive, non-iterative) formula for Fibonacci numbers:
Fib(n) = (pow((1+sqrt(5))/2, n) + pow((1-sqrt(5))/2, n)) / sqrt(5)
It turns out that for all n >= 0
, you can simplify this formula to:
Fib(n) = round(pow((1+sqrt(5))/2, n) / sqrt(5))
Knowing this, you can use following simple implementation for fibcalc
:
public static double fibcalc(int num) {
return Math.floor(Math.pow((1+Math.sqrt(5))/2, num) / Math.sqrt(5) + 0.5);
}
回答3:
You can also use the following calculator to calculate the Fibonacci sequence (using Javascript): enter link description here
来源:https://stackoverflow.com/questions/15892801/fibonacci-calculation