在 if
条件内,我有 num1
和 num2
,检查它们是否可以除以 2 以确定它们是否是否奇怪。正如您所看到的,我正在检查当除以 2 时,num1
和 num2
的答案是否都是 0。我不确定为什么当我输入 num2
参数作为偶数时它的计算结果为 true
。
function areBothOdd(num1, num2) {
if(num1 % 2 === 0 && num2 % 2 === 0){
return false;
}
else {
return true;
}
}
var output = areBothOdd(7, 4);
console.log(output); // --> true
为什么我得到true
?
为什么这段代码的计算结果为 false?
function areBothOdd(num1, num2) {
if(num1 % 2 !== 0 && num2 % 2 !== 0){
return true;
}
else {
return false;
}
}
var output = areBothOdd(7, 4);
console.log(output); // --> false
最佳答案
您需要逻辑“或”||
,而不是逻辑“与”。
您的测试
num1 % 2 === 0
对于偶数返回 true
,因为偶数除以 2
余数为 0
。
function areBothOdd(num1, num2) {
if (num1 % 2 === 0 || num2 % 2 === 0) {
return false;
} else {
return true;
}
}
console.log(areBothOdd(7, 4)); // --> false
console.log(areBothOdd(7, 5)); // --> true
console.log(areBothOdd(4, 4)); // --> false
对于逻辑 AND 的检查,您需要对各个部分取反并将逻辑运算符从 OR 更改为 AND,如 De_Morgan's laws描述了转变。
num1 % 2 === 0 || num2 % 2 === 0 both parts
num1 % 2 !== 0 && num2 % 2 !== 0 are equal
^^^^ ^^ ^^^
function areBothOdd(num1, num2) {
if (num1 % 2 !== 0 && num2 % 2 !== 0) {
return false;
} else {
return true;
}
}
console.log(areBothOdd(7, 4)); // --> false
console.log(areBothOdd(7, 5)); // --> true
console.log(areBothOdd(4, 4)); // --> false
关于Javascript 逻辑运算符 AND 在 'if' 条件内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44018874/