生成 Java 中斐波那契数列的第 N 个值

Producing the Nth value of Fibonacci Sequence in Java

这是我正在 运行 打印斐波那契数列的第 n 个值的程序,但我遇到了一个问题,即当我输入我定义的无效值时,它仍然运行循环方法。例如,如果我输入 0,它将打印:

“不是一个有效的数字 斐波那契数列的0值为0

希望有人能指出我的错误所在,我已经检查了所有的括号,但我找不到错误的地方

//position is user input for nth position, fold2 and fnew will calculate fSequence to find value

int position, fold1, fold2, fNew, loopCount;

//telling user what program will do and stipulations on how to get program to execute correctly
System.out.println("This program will tell you the nth value of the Fibonacci sequence.");
System.out.println("Enter an integer (1 - 46):");
position = keyboard.nextInt();

fold1 = 0;
fold2 = 1; 

//setting upper parameters for limit on given positions
if (position < 1 || position > 46){
    System.out.println("Not a valid number");
} 
else {
    for (loopCount = 0; loopCount < position; loopCount++ ){
        fNew = fold1 + fold2;
        fold1 = fold2;
        fold2 = fNew;                       
    }
}

System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1);

你的最后一个 System.out.println 在你的 else 之外,因此它总是被调用。你应该把它移到 else.

你得到了这条线:

 System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1);

在else之后,所以它甚至在if语句之后,因此它会在所有情况下执行,最后放在else括号内。

你的 System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1);else 范围之外,因此无论条件如何都执行。

您的代码应为,

 if (position < 1 || position > 46){
        System.out.println("Not a valid number");
    } 
    else {
        for (loopCount = 0; loopCount < position; loopCount++ ){
            fNew = fold1 + fold2;
            fold1 = fold2;
            fold2 = fNew;
            System.out.println("The " + position + " of the Fibonacci Sequence is " + fold1);                       
        }
    }