简体   繁体   English

为什么我的比较没有产生预期的结果?

[英]Why is my comparison not producing the expected result?

I'm expecting this to output "Failed" but instead it outputs "Excellent", even though the value being compared doesn't match that comparison.我期待 output “失败”,但它输出“优秀”,即使正在比较的值与该比较不匹配。

What's wrong with my code?我的代码有什么问题?

 let grade = 99; if(140 <= grade <= 150) { console.log('Excellent'); } else if(100 <= grade) { console.log('Very Good'); } else if(grade < 100) { console.log('Failed'); }

This is not how multiple comparisons are made:这不是进行多重比较的方式:

if (140 <= grade <= 150)

In this case the first half would evaluate to true or false and the rest would be something like true <= 150 which makes little sense.在这种情况下,前半部分将评估为truefalse ,而 rest 将类似于true <= 150 ,这没有什么意义。

Instead, rather than think of it in terms of intuition, think of it in terms of combining logical operations.相反,与其从直觉的角度来思考,不如从逻辑运算的组合来思考。 The two operations you want are:您想要的两个操作是:

  • 140 <= grade
  • grade <= 150

Combine those with the "and" operator:将它们与“and”运算符结合起来:

if (140 <= grade && grade <= 150)

Result:结果:

 let grade = 99; if (140 <= grade && grade <= 150) { console.log('Excellent'); } else if(100 <= grade) { console.log('Very Good'); } else if(grade < 100) { console.log('Failed'); }

If you meant to check whether the grade is between 140 and 150 by 140 <= grade <= 150 then you are doing it the wrong way.如果您打算通过140 <= grade <= 150检查成绩是否在 140 和 150 之间,那么您的做法是错误的。 This will evaluate 140 <= grade first, which will return either zero or one, which will then be compared to 150 (and hence will always be smaller).这将首先评估140 <= grade ,它将返回零或一,然后将其与 150 进行比较(因此总是更小)。 You need to use two separate statements:您需要使用两个单独的语句:

if(140 <= grade && grade <= 150) {
  ...
}

Do it like this.像这样做。 You need to separate two condition which you provided in the first if statement.您需要将您在第一个 if 语句中提供的两个条件分开。

 let grade = 99; if(140<= grade && grade <=150){ console.log('Excellent'); } else if(100<= grade){ console.log('Very Good'); } else if(grade < 100){ console.log('Failed'); }

Expression 140 <= grade <= 150 is correct in mathematical form.表达式140 <= grade <= 150在数学形式上是正确的。 In js you must write it as 140 <= grade && grade <=150在 js 中你必须写成140 <= grade && grade <=150

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM