Spot De Morgan's Law Bug
找错误 中等
题目
This code should print "无效" when age is NOT (18 or older AND has license), but the logic is wrong. What is the issue?
代码
let age = 16;
let hasLicense = false;
if (!(age >= 18) && !hasLicense) {
console.log("Invalid");
}
提示
De Morgan's Law: NOT (AND B) = (NOT) OR (NOT B).
解释
通过 De Morgan's Law, !(&& B) 是 equivalent 到 ! || !B, 不 ! && !B. code uses && 相反的 ||. 使用 age=16 and hasLicense=假: !(16>=18) 是真, !假是 真, 所以真 && 真 = 真 — 它 happens 到工作这里, 但 consider age=16, hasLicense=真: 原始 !(age>=18 && hasLicense) = !(假) = 真 (无效), 但 !age>=18 && !hasLicense = 真 && 假 = 假 (misses 它). fix 是 如果 (!(age >= 18) || !hasLicense).
相关资源
相关课程
- 布尔值 Logic
学习关于布尔值 logic and 运算符.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。