【发布时间】:2016-01-02 05:36:33
【问题描述】:
这是我的代码,它告诉您询问的递增斐波那契数,并在您插入“-1”时停止,一切正常。我需要它一直告诉我相同的数字,但如果我插入 ex。 12 它说:89,这是正确的。但是我第二次这样做时,它给了我 10946 等等,总是增加。想法如何解决这个问题并让 89 或其他数字保持不变?
int first= 0;
int second= 1;
int next= 0;
Scanner scanner = new Scanner(System.in);
System.out.println("tell the fibonacci number you want to know:");
while(true){
int fib= scanner.nextInt();// 0, 1, 1, 2, 3, 5, 8, 13, 21
if(fib== -1){ System.out.println("program ends");break;}
else if(fib== 2)System.out.println("1");
else{
if(fib==0){System.out.println("error, tell fibonacci one more time: ");
continue; //This will jump to the next loop of while, asking the number fib. Not really necessary with the if else construct done here.
}
else{
for(int count= 3; count<=fib;count++){
next= first+second;
first= second;
second=next;}
System.out.println(next);
}
【问题讨论】:
-
你认为
while (true)是做什么的?你认为这个循环会在什么情况下退出? -
在相关说明中,您说在尝试实现循环逻辑时“出现错误/意外循环”。那可能是什么错误?
标签: java loops for-loop while-loop fibonacci