gpt4 book ai didi

java - 调试我的递归斐波那契 Java 代码并更正逻辑

转载 作者:行者123 更新时间:2023-12-01 19:35:49 26 4
gpt4 key购买 nike

我无法理解为什么输出是错误的。

我尝试编写一个打印斐波那契数的递归代码,并得到了预期的输出和意外值流。

public class FibonacciSeries {

static int limitNum = 10; //the desired number of Fibonacci values

public static void main(String[] args) {
FibonacciSeries series = new FibonacciSeries();
series.printRecursiveFibonacci(0,1,1);
}

public void printRecursiveFibonacci(int a, int b, int count)
{
while(count<=limitNum)
{
if(count==1||count==2)
{
System.out.println(count-1);
count++;
continue;
}

int k=a+b;
a=b;
b=k;
System.out.println(b);
count++;
printRecursiveFibonacci(a, b, count);
}
}

}

预期输出是0112358132134

但我得到了 -01123581321343421343413213434213434813213434213434132134342134345813213434213434132134342134348132134342134341321343421343435813213434213434132134342134348132134342134341321343421343458132134342134341321343421343481321343421343413213434213434235813213434213434132134342134348132134342134341321...

最佳答案

我不确定您的代码中究竟发生了什么,发生了很多奇怪的事情:

  • while 和同一方法中的递归
  • ifContinue 而不是 if/else
  • 有时打印count - 1,有时打印b

我怀疑这与您的循环未按预期终止有关。一般来说,尝试坚持递归循环。这是一个示例实现:

public static void printFibLimit(int a, int b, int count) {
if (count >= EXTERNALLY_DEFINED_LIMIT_VARIABLE) return; // if true, we're done, no more work has to be done.
// Since this is a tail-recursive function, return will terminate the function

System.out.println(a); // print our first value

printFibLimit(b, a + b, count + 1);
// a -> b
// b -> a + b
// count -> count + 1

}

关于java - 调试我的递归斐波那契 Java 代码并更正逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57641211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com