gpt4 book ai didi

java - 虽然循环条件未给出预期结果

转载 作者:行者123 更新时间:2023-12-01 11:42:54 24 4
gpt4 key购买 nike

我正在编写斐波那契数列,除了我无法根据 while 条件(当输出 < maxOutput)限制输出之外,一切正常,无法将我的输出限制为用户输入的值。我的 while 条件在哪里出错了。请参阅下面的代码

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

}
}
}

最佳答案

这应该有效:

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

...希望我能帮助你!

关于java - 虽然循环条件未给出预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378190/

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