【发布时间】:2016-08-01 00:49:23
【问题描述】:
好的,我正在尝试编写一个程序来输出每个斐波那契数。但是我的数字总是从 fib(2) 开始,我将使用 next() 来获取下一个斐波那契数。
public class Fibonacci {
static int NextCounter = 2; // fib(2)
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter your number!");
try {
FibonacciPrint(System.in.read());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void FibonacciPrint (int a){
for(int i = 0 ; i < a ; i++ ){
System.out.println(next()); // Will never stop?
}
}
private static int next() {
int result = fibo(NextCounter);
NextCounter += 1;
return result;
}
private static int fibo (int n){
if( n == 1 || n == 2)
{
return 1;
}
return fibo(n-1) + fibo (n-2);
}
}
所以我希望当 i 等于 a 时 for 循环将停止。正如你可能已经知道它不会。为什么 ? next() 和 fibo() 工作正常。感谢您的帮助。
我在一秒钟后停止的跑步后的结果:
Enter your number!
5 // Input
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
9227465
14930352
24157817
39088169
63245986
102334155
【问题讨论】:
-
首先,您的代码应该永远有:
catch (IOException e) {}-- 空的 catch 块,永远。你会闭着眼睛开车吗? -
它打印什么吗?
a的值是多少?你有没有尝试过它? -
@Blorgbeard 是的,我会得到每个斐波那契数。 A 应该是用户输入。
-
是的,但是
a的值是是多少?设置断点,检查代码! -
我注意到,在运行时检查
a的值会发现 @Paul 在下面的回答中指出的问题 - 调试是一项重要的学习技能!