这个小应用程序可以告诉驾驶员驱动程序运行的速度,当我测试该代码时,它只会警告第一个条件,无论我输入的内容是什么,而且这是一个严重的错误,这是我感谢所有帮助的代码提前给所有人
alert(
"Welcome this program tells you how fast you were driving your
vehicle, in km/h");
var top_speed = parseInt(prompt("How many km/h you was at?"));
if (top_speed >= 60) {
alert("You were driving at " + top_speed + "km/h thats a normal speed");
} else if (top_speed >= 80) {
alert("You were driving at " + top_speed + "km/h thats a moderate
speed");
} else if (top_speed >= 120) {
alert("You were driving at " + top_speed + "km/h that is a very high
speed");
} else {
alert("You need to go faster " + top_speed + "km/h is too slow ");
}
答案 0 :(得分:3)
语句从上到下进行评估。由于80和120均为>= 60
,因此第一个条件将始终与60或更高的值匹配。
只需切换顺序:
if (top_speed >= 120) {
alert("You were driving at " + top_speed + "km/h that is a very high
speed");
} else if (top_speed >= 80) {
alert("You were driving at " + top_speed + "km/h thats a moderate
speed");
} else if (top_speed >= 60) {
alert("You were driving at " + top_speed + "km/h thats a normal speed");
} else {
alert("You need to go faster " + top_speed + "km/h is too slow ");
}
一种替代方法是根据您的情况进行更具体的说明,即也包括一个上限:
if (top_speed >= 60 && top_speed < 80) {
alert("You were driving at " + top_speed + "km/h thats a normal speed");
} else if (top_speed >= 80 && top_speed < 120) {
alert("You were driving at " + top_speed + "km/h thats a moderate
speed");
} else if (top_speed >= 120) {
alert("You were driving at " + top_speed + "km/h that is a very high
speed");
} else {
alert("You need to go faster " + top_speed + "km/h is too slow ");
}
答案 1 :(得分:0)
这是因为只要其他两个条件top_speed >= 60
和true
都为真,则第一个条件top_speed >= 80
为top_speed >= 120
。只要任何一个条件为true
它不会检查低于此值的其他内容。您应该更改顺序。
var top_speed = parseInt(prompt("How many km/h you was at?"));
if (top_speed >= 120) {
alert("You were driving at " + top_speed + "km/h that is a very high speed");
}
else if (top_speed >= 80) {
alert("You were driving at " + top_speed + "km/h thats a moderate speed");
}
else if (top_speed >= 60) {
alert("You were driving at " + top_speed + "km/h thats a normal speed");
}
else {
alert("You need to go faster " + top_speed + "km/h is too slow ");
}
答案 2 :(得分:0)
您需要撤销检查条件:
试想一下,当您输入140
时,该值大于60
,因此代码将在第一个if
条件下输入,而不会检查其他任何条件。
alert("Welcome this program tells you how fast you were driving your vehicle, in km/h");
var top_speed = parseInt(prompt("How many km/h you was at?"));
if (top_speed >= 120)
{
alert("You were driving at " + top_speed + "km/h thats a very high speed");
}
else if (top_speed >= 80)
{
alert("You were driving at " + top_speed + "km/h thats a moderate speed");
}
else if (top_speed >= 60)
{
alert("You were driving at " + top_speed + "km/h that is a normal speed");
}
else
{
alert("You need to go faster " + top_speed + "km/h is too slow ");
}
答案 3 :(得分:0)
除了这里已经有好的答案(它们是正确的答案)之外,我认为在其他人遇到类似问题的情况下,我也应该提及这一点。
否则,仅当第一个条件为false时才执行。也就是说,一串其他ifs只会执行FIRST true条件。如果不存在,则仅执行else;否则,则不执行任何操作。