<html>
<head>
<title>Greatest of three</title>
</head>
<body>
<script type="text/javascript">
var a = parseInt(prompt("Enter A"));
var b = parseInt(prompt("Enter B"));
var c = parseInt(prompt("Enter C"));
if(a == b && b == c)
document.write("A , B and C are equal! Give distinct numbers.")
else if(a == b)
document.write("A and B are equal! Give distinct numbers.");
else if(b == c)
document.write("B and C are equal! Give distinct numbers.");
else if(c == a)
document.write("A and C are equal! Give distinct numbers.");
else if(a > b) {
if(a > c)
document.write("A is the greatest");
else
document.write("B is the greatest");
}
else {
if(b > c)
document.write("B is the greatest");
else
document.write("C is the greatest");
}
</script>
</body>
</html>
为什么没有作为输入给出“C是最大的”? 如果我在给出NULL时必须打破它,我该怎么做?
答案 0 :(得分:7)
如果没有输入任何内容,则此行代码
var a = parseInt(prompt("Enter A"));
将为NaN
(以及其他变量)返回值a
。
由于NaN == NaN
和NaN < NaN
都未导致true
,所有if
- 语句都将解析为else块,最终会产生document.write("C is the greatest");
要检查此用途isNaN()
,请执行以下操作:
if ( isNaN( a ) ) {
// some code to handle this
}
答案 1 :(得分:2)
如果您没有提供任何提示;然后a = parseInt(prompt("Enter A"))
使a = NaN
(NaN表示不是数字)。然后条件失败; NaN < NaN
与NaN == NaN
一样是假的。基本上任何一方是NaN的比较都将是假的。通过你的逻辑,将打印“C是最伟大的”
答案 2 :(得分:1)
if(b>c)
document.write("B is the greatest");
else
document.write("C is the greatest");
此处在整个逻辑中,您只是检查a>b
,a>c
...但您没有检查NaN
,要检查值是NaN
,使用isNaN()
答案 3 :(得分:0)
在三元逻辑中,涉及Null的关系总是返回false。甚至比较两个Null值。 Javascript中的NaN值遵循这些规则。
因此始终采用else
路径。
答案 4 :(得分:0)
因为这会被触发。
else
{
if(b>c)
document.write("B is the greatest");
else
document.write("C is the greatest");
}
如果没有输入b
会== c
,那么最后的else
(C是最大的)会被触发。
您需要检查是否有输入。你可以通过在整个事物周围包裹一个额外的块来实现这一点:
if( a && b && c ) {
// your if statements
}
else {
alert("No input!")
}
答案 5 :(得分:0)
Becaus a = NaN
比较NaN == NaN是假的!
<body>
<script type="text/javascript">
var a = parseInt(prompt("Enter A"));
var b = parseInt(prompt("Enter B"));
var c = parseInt(prompt("Enter C"));
document.write(a);// << os NaN
document.write(a == b); //<< Is False!!
if(a==b && b==c)
document.write("A , B and C are equal! Give distinct numbers.")
else if(a==b)
document.write("A and B are equal! Give distinct numbers.");
else if(b==c)
document.write("B and C are equal! Give distinct numbers.");
else if(c==a)
document.write("A and C are equal! Give distinct numbers.");
else if(a>b)
{
if(a>c)
document.write("A is the greatest");
else
document.write("B is the greatest");
}
else
{
if(b>c)
document.write("B is the greatest");
else
document.write("C is the greatest");
}
</script>
</body>