用Java生成Fibonacci序列的第N个值

时间:2016-10-24 00:22:44

标签: java fibonacci

这是我正在运行的程序,用于打印Fibonacci序列的第n个值,但是我遇到的问题是,当我输入一个无效的值时,它仍然以任何方式运行循环。例如,如果我输入0,它将打印:

"不是有效号码 Fibonacci序列的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);

3 个答案:

答案 0 :(得分:1)

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);                       
        }
    }   

答案 1 :(得分:0)

您的上一个System.out.println位于else之外,因此始终会被调用。您应该将其移至else

答案 2 :(得分:0)

你有这条线:

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

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