如何在不使用递归的情况下使用 int return 类型的方法 return FIbonacci 数列?
How can I return the FIbonacci sequence using an int return type method without using recursion?
我正在尝试在 Java 中创建一个方法,打印 fib 系列直到传递给该方法的数字。我的问题是我需要使用 int return 类型来 return 系列,我 不能使用递归 .
我的第一个想法
我最初的想法如图所示。哪个工作得很好。它采用 int 和 returns void 类型的参数,只是在计算时打印数字。
public void fibonacci(int num) {
int a = 0;
int b = 0;
int c = 1;
for (int i = 0; i < num; i++) {
a = b;
b = c;
c = a + b;
System.out.print(c + ", ");
}
}
提问的内容
下面的代码显示了我的任务。它要求一个方法,该方法采用类型 int 和 returns 类型的参数 int.
public int fibonacci(int num) {
//some code...
return x; //This is what confuses me. I know this isn't right.
}
对我来说,这似乎不切实际,甚至可能无法使用 int return 类型。我想知道是否有人知道这是可能的方法。
预期输出:
//Method call in driver class.
fibonacci(5);
//This would print to console.
1, 1, 2, 3, 5
您可以使用等式 [(h)^a - (j)^a] * [1/sqrt(5)]
。
'a'
是想要的斐波那契数
'h'
是 [1 + sqrt(5)] / 2
'j'
是 [1 - sqrt(5)] / 2
public static int returnFibonacci(int a) {
double firstTerm; // calculate h
double secondTerm; //calculate j
double fib; //calculate 1/sqrt(5) with firstTerm and secondTerm
}
我正在尝试在 Java 中创建一个方法,打印 fib 系列直到传递给该方法的数字。我的问题是我需要使用 int return 类型来 return 系列,我 不能使用递归 .
我的第一个想法
我最初的想法如图所示。哪个工作得很好。它采用 int 和 returns void 类型的参数,只是在计算时打印数字。
public void fibonacci(int num) {
int a = 0;
int b = 0;
int c = 1;
for (int i = 0; i < num; i++) {
a = b;
b = c;
c = a + b;
System.out.print(c + ", ");
}
}
提问的内容
下面的代码显示了我的任务。它要求一个方法,该方法采用类型 int 和 returns 类型的参数 int.
public int fibonacci(int num) {
//some code...
return x; //This is what confuses me. I know this isn't right.
}
对我来说,这似乎不切实际,甚至可能无法使用 int return 类型。我想知道是否有人知道这是可能的方法。
预期输出:
//Method call in driver class.
fibonacci(5);
//This would print to console.
1, 1, 2, 3, 5
您可以使用等式 [(h)^a - (j)^a] * [1/sqrt(5)]
。
'a'
是想要的斐波那契数'h'
是 [1 + sqrt(5)] / 2'j'
是 [1 - sqrt(5)] / 2
public static int returnFibonacci(int a) {
double firstTerm; // calculate h
double secondTerm; //calculate j
double fib; //calculate 1/sqrt(5) with firstTerm and secondTerm
}