所以我正在使用readline-sync来执行基本计算。乘法和除法工作正常,但是当我将两个数字相加时,它只是将它们连接起来,当我减去时,它返回NaN。
知道我在做什么错吗?
这是我的代码:
var readlineSync = require("readline-sync");
var enterNum1 = readlineSync.question("Please enter your first number: ");
var enterNum2 = readlineSync.question("Please enter your second number: ");
var operations = ["add", "sub", "mul", "div"];
var selectOperation = readlineSync.keyInSelect(operations, "What operation will you like to perform?");
function addNum(num1, num2){
console.log("The result is : " + Number(num1) + Number(num2));
}
function subNum(num1, num2){
console.log("The result is : " + Number(num1) - Number(num2));
}
function mulNum(num1, num2){
console.log( "The result is : " + Number(num1) * Number(num2));
}
function divNum(num1, num2){
console.log("The result is : " + Number(num1) / Number(num2));
}
if(selectOperation === 0){
addNum(enterNum1, enterNum2);
}else if(selectOperation === 1){
subNum(enterNum1, enterNum2)
}else if(selectOperation === 2){
mulNum(enterNum1, enterNum2);
}else {
divNum(enterNum1, enterNum2);
}
最佳答案
只需将操作括在方括号中
例如
console.log("The result is : " + (Number(num1) + Number(num2)));
console.log("The result is : " + (Number(num1) - Number(num2)));
推理
根据运算符的优先级,乘法和除法的优先级较高,即它们将首先执行。在加法和减法的情况下,优先级相同,并且从左到右进行操作。因此,首先将字符串
"The result is : "
添加到Number(num1)
中,然后添加到Number(num2)
中,这会导致串联,并且要进行减法,它会尝试从字符串中减去一个数字,从而导致NaN
供引用,Operator precedence
关于javascript - 为什么我的加减法不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50055435/