我正在编写Fibonacci系列,每一件事都运行正常,但我没有限制输出符合while条件(输出< maxOutput)无法将输出限制为用户输入的值。我在哪里得到我的条件错误。请参阅下面的代码
import java.util.Scanner;
public class Fibonacci {
private static int fib(int prev_Total, int current_Num) {
return current_Num + prev_Total; // return sum of the two
}
public static void main(String[] args){
int f_Num, s_Num, maxOutput;
Scanner maxNum = new Scanner(System.in);
System.out.println("Enter the first value: ");
f_Num = maxNum.nextInt();
System.out.println("Enter the second value: ");
s_Num = maxNum.nextInt();
System.out.println("Enter the maximum value of the series: ");
maxOutput = maxNum.nextInt();
System.out.println(f_Num); // print the first value by default
System.out.println(s_Num); // print the second value by default
int prevTotal = f_Num; // initialise prevTotal
int currentNum = s_Num; // initialise currentTotal
int output = 0; // initialise output
while (output < maxOutput) {
output = fib(currentNum, prevTotal); // assign the result of first two numbers added together to first output
prevTotal = currentNum; // update prevTotal (currentNum becomes our new prevTotal)
currentNum = output; // update currentNum (output becomes our new currentNum)
System.out.println(output); // print output
}
}
}
答案 0 :(得分:1)
这应该有效:
while (true) {
// assign the result of first two numbers added together to first output
output = fib(currentNum, prevTotal);
// update prevTotal (currentNum becomes our new prevTotal)
prevTotal = currentNum;
currentNum = output;
if (output > maxOutput) {
break;
}
// print output
System.out.println(output);
}
...希望我帮助过你!
答案 1 :(得分:0)
反转循环,使用do .. while()它将起作用。
编辑:
放入System.out.println(输出);在循环的第一行,在while之后,如:
while (output < maxOutput){
System.out.println(output); // print output
...
答案 2 :(得分:0)
你的for循环应该有点像:
while (output < maxOutput){
System.out.println(output); // print output
output = fib(currentNum, prevTotal); // assign the result of first two numbers added together to first output
prevTotal = currentNum; // update prevTotal (currentNum becomes our new prevTotal)
currentNum = output; // update currentNum (output becomes our new currentNum)
}
编辑: 逻辑上的轻微编辑可以解决
int output = 0;
int prevTotal = s_Num; // initialise prevTotal
int currentNum = output = fib(f_Num, prevTotal); // initialise currentTotal with output
while (output < maxOutput){
System.out.println(output); // print output
output = fib(currentNum, prevTotal); // assign the result of first two numbers added together to first output
prevTotal = currentNum; // update prevTotal (currentNum becomes our new prevTotal)
currentNum = output; // update currentNum (output becomes our new currentNum)
}