我在我的代码中有一条评论来解释我的最终结果是什么,但请不要在回答这个问题时回答我如何实现这个目标。
基本上,我有一个标记为“currentNum”的 int,它等于 1。我有一个 while 循环要执行,直到 currentNum 小于 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);
}
}
}