问题描述
我最近做了一个计算器,直到我为负运算符计算结果时NaN开始显示为止,它一直可以正常工作。我正在测试代码,一切正常,然后重新加载了选项卡,突然NaN开始显示在减号运算符中。请说明为什么会这样以及如何解决。
function btn001() {
var firstNumber1 = firstNumber.value;
var operator1 = operator.value;
var secondNumber1 = secondNumber.value;
if (operator1 == "-") {
document.getElementById("result").innerHTML = "=" + firstNumber1- secondNumber1;
}
else if (operator1 == "+") {
document.getElementById("result").innerHTML = "=" + firstNumber1+secondNumber1;
}
else if (operator1 == "/") {
document.getElementById("result").innerHTML = "=" + firstNumber1/secondNumber1;
}
else if (operator1 == "*") {
document.getElementById("result").innerHTML = "=" + firstNumber1*secondNumber1;
}
else if (operator1 == "Ũ") {
document.getElementById("result").innerHTML = "=" + firstNumber1*secondNumber1;
}
else if (operator1 == "ũ") {
document.getElementById("result").innerHTML = "=" + firstNumber1/secondNumber1;
}
else {
document.getElementById("result").innerHTML = "Error 414! " + "Invalid Operator or value";
}
}
body {
background-color: green;
}
.operator {
width: 160px;
height: 60px;
font-size: 40px;
}
.button {
font-size: 40px;
background-color: white;
}
.button:hover {
font-size: 41px;
background-color: yellow;
}
.values {
height: 60px;
width: 760px;
font-size: 40px;
}
.result {
width: 1300px;
height: 190px;
border: 5px solid yellow;
text-align: center;
border-radius: 80px;
color: white;
font-size: 90px;
}
<!DOCTYPE html>
<html>
<head>
<title> Calculate it! </title>
</head>
<body>
<input type="number" id="firstNumber" placeholder="First value" class="values"> <br>
<input type="text" id="operator" placeholder="operator" class="operator"><br>
<input type="number" id="secondNumber" placeholder="Second value" class="values"> <br> <br>
<button onclick="btn001()" id="submit" class="button"> Calculate Result </button> <br> <br>
<p id="result" class="result">0</p>
</body>
</html>
解决方法
/
和*
运算符之所以起作用,是因为变量会自动转换为int,并且此运算会在求和之前执行。
当您向字符串中添加任何内容时,其余部分将被转换为字符串,因此仅将它们转换为int就不够了(因为您将得到"=" + 10 + 20
这样的女巫,它们将被转换为{{1} }或"=" + "10" + 20 = "=10" + "20"
为-
,而"=" + "10" - 20
仍不是数字。
为了使其工作,可以转换数字并使用括号。像这样:
"=10" - 20
您还可以从以下位置替换 function btn001() {
var firstNumber1 = +firstNumber.value;
var operator1 = operator.value;
var secondNumber1 = +secondNumber.value;
if (operator1 == "-") {
document.getElementById("result").innerHTML = "=" + (firstNumber1- secondNumber1);
}
else if (operator1 == "+") {
document.getElementById("result").innerHTML = "=" (firstNumber1+secondNumber1);
}
...
+
和var firstNumber1 = +firstNumber.value;
与var secondNumber1 = +secondNumber.value;
函数(作为另一个响应;它也可以正常工作)。但是您将需要使用肢体感觉。