我在我的代码中有一个评论来解释我最终的结果是什么,但请不要回答我在回答这个问题时如何实现这个目标。
基本上,我有一个标有“currentNum”的int,它等于1.我有一个while循环要执行,直到currentNum少于四百万。但是,由于某种原因,循环没有执行。 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);
}
}
}
答案 0 :(得分:7)
错误在这一行:
while(currentNum < 4000000);
最后;
错位了!在while
条件之后,你应该在循环结束时放置一个开口{
,然后是另一个}
,以便关闭该块。像这样:
while (currentNum < 4000000) {
// body
}
答案 1 :(得分:1)
语法错误。正确的语法是:
do{
//put your codes here
}
while(currentNum < 4000000);
或
while(currentNum < 4000000){
//put your codes here
}
答案 2 :(得分:0)
使用;
声明语句结束。试试这个:
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);
}
}
}
}
答案 3 :(得分:0)
我相信这一行就是你的问题所在
while(currentNum < 4000000);
这会导致无限循环,因为“currentNum”永远不会增加。
while(currentNum < 4000000);
==
while(currentNum < 4000000){
}