gpt4 book ai didi

java - “While”循环未执行?

转载 作者:行者123 更新时间:2023-12-02 01:23:54 27 4
gpt4 key购买 nike

我的代码中有一条注释来解释我想要的最终结果是什么,但请不要在回答这个问题时回答我如何实现该目标。

基本上,我有一个标记为“currentNum”的 int,它等于 1。我有一个 while 循环,要执行到 cu​​rrentNum 小于 400 万为止。但是,由于某种原因,循环没有执行。 while 循环之外的所有内容都会执行,但 while 循环本身不会执行。

控制台上显示一次“HI”。控制台中不显示“LOOP”。

代码:

 /*Each new term in the Fibonacci sequence is generated by adding the previous two terms. 
* By starting with 1 and 2, the first 10 terms will be:
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.*/

public class Solution {

public static void main(String args[]) {

int lastNum1 = 0;
int lastNum2 = 0;
int currentNumEven = 0;
int currentNum = 1;
int sumEven = 0;
boolean last = true;

System.out.println("HI");

while(currentNum < 4000000);

System.out.println("LOOP");

currentNum = currentNum + (lastNum1 + lastNum2);

if(last) {
lastNum1 = currentNum;
last = !last;
} else {
lastNum2 = currentNum;
last = !last;
}

if(currentNum % 2 == 0) {
currentNumEven = currentNum;
sumEven += currentNum;
System.out.println(currentNumEven);
System.out.println(currentNum);
}

if(currentNum < 4000000) {
currentNum++;

} else {
System.out.println("Sum of all even Fibonacci values: " + sumEven + "\n Last even number of sequence below 4,000,000" + currentNumEven);
}

}

}

最佳答案

错误在这一行:

 while(currentNum < 4000000);

最后一个;放错地方了!在 while 条件之后,您应该放置一个开始 {,然后在循环末尾放置另一个 },以关闭该 block 。像这样:

while (currentNum < 4000000) {
// body
}

关于java - “While”循环未执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226656/

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