gpt4 book ai didi

java - 斐波那契数列检测器 Java

转载 作者:行者123 更新时间:2023-11-30 03:41:49 24 4
gpt4 key购买 nike

我的 Java 入门类(class)的斐波那契数列程序遇到问题。仅当我按升序输入数字时它才有效。

目标:必须使用 while 循环,必须检测数字是否是斐波那契数,并且必须检测序列中数字的顺序。如果它不是斐波那契数,则必须如此说明,并说明它位于哪些数字之间。程序还必须不断要求输入数字,直到用户退出

输出示例:

Please input a number for analysis >> 2
2 is a fibonacci number whose order in the sequence is 4
Please input a number for analysis >> 53
53 is not a fibonacci number
However, it lies between the Fibonacci numbers 34 (order:10) and 55 (order:11)

我的问题:该程序仅在我按升序键入输入数字时才起作用。例如,如果我输入 5,它会告诉我这是一个带有 seq 的 fib 数字。的 6。但是当我输入 2 时,它说这不是斐波那契数,但它位于斐波那契数 3(阶数:5)和 5(阶数:6)之间。当我输入 55 时,它告诉我这是一个虚假数字。但是我无法输入任何低于 55 的数字而不显示错误的输入。

我认为问题出在 else if 语句上,可能是 (fibnext != testnum)。或者也许是计数?谁能指出我可能出现问题的方向?

import java.util.Scanner;

public class Fibonacci
{
public Fibonacci()
{
int fibhigh = 1;
int fiblow = 0;
int count = 2;
int fibnext = 0;
Scanner input = new Scanner(System.in);
boolean quit = false;

System.out.println("Welcome to Fibonacci Sequence Dectector");
while(!false)
{
System.out.print("Please input a number for analysis >> ");
int testnum = input.nextInt();

if(testnum < 0)
{
System.out.println("Please enter a positive number");
continue;
}
while(fibnext < testnum)
{
fibnext = fibhigh + fiblow;
fiblow = fibhigh;
fibhigh = fibnext;
count++;
}
if(fibnext == testnum)
{
System.out.println(testnum + " is a fibonacci number whose order in the sequence is " + count);
}
else if(fibnext != testnum) System.out.println(testnum + " is not a fibonacci number \nHowever, it lies between the Fibonacci numbers " + fiblow + " (order:" + (count - 1) + ") and " + fibhigh + " (order:" + count + ")");
}
}
}

最佳答案

你永远不会重置变量int fibhigh = 1,fiblow = 0,count = 2,fibnext = 0;

您应该移动此代码片段

int fibhigh = 1;
int fiblow = 0;
int count = 2;
int fibnext = 0;

在循环开始时:

while (!false) {  }

关于java - 斐波那契数列检测器 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694220/

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