package zh.codegym.task.task04.task0416;
/*
蒙眼过马路
*/
import java.io.*;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
//在此编写你的代码
boolean b = true;
double num = input();
while (b == true) {
if (num >= 0 && num <= 4) {
if (num >= 0 && num < 3) {
System.out.println("绿灯");
} else {
if (num >= 3 && num < 4) {
System.out.println("黄灯");
}
if (num >= 4 && num < 5) {
System.out.println("红灯");
}
}
b = false;
} else
num -= 5;
}
}
public static Double input() {
Scanner scanner = new Scanner(System.in);
return scanner.nextDouble();
}
}
wedfrgt
第 8 级
为什么以我的代码,本地运行时一切正常,而当我去点击验证的时候,提示有无限循环?
已解决
评论 (4)
- 受欢迎
- 新
- 旧
你必须先登录才能发表评论
云梦
22 二月 2021, 14:26
如果num在4(不包含)到5(不包含)之间就会出现无限循环的问题
比如 num = 4
第一次循环
第一个判断if(num >= 0 && num < 3),判断不满足转跳到else
num = num -5 //num = 4-5 = -1
第二次循环
第一个判断if(num >= 0 && num < 3),判断不满足转跳到else
num = num -5 //num = -1-5 = -6
这样就会一直进行循环
把第一个判断条件改为num >= 0 && num < 5 就可以了
还有一个建议就是再写这种区间判断的时候推荐下面这样子些更加容易理解
if(0 <= num && num < 5)
+1
wedfrgt
23 二月 2021, 09:08
是的,我现在看出我哪里有错了,非常感谢!
然后对于你的那个建议,我觉得确实更容易理解,再次感谢!XD
0
Guadalupe Gagnon
22 二月 2021, 14:18
The problem with this code is 17. If the user enters anything between 4.1 and 4.9 (or anything that continually subtracting 5 will result in 4.1 to 4.9) this line will be false, line 30 will subtract 5 from the number, the new number will be less than 0, then line 17 will always be false since once you get to a negative number the code just subtracts 5 from that infinitely. You will need to revisit the logic to prevent this from happening.
0
wedfrgt
23 二月 2021, 09:06
After listening to your point of view, I found my mistake, thank you very much!
0