<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="num1" placeholder="请输入数值"/>
<input type="text" id="opt" placeholder="请输入操作符:+,-,*,/"/>
<input type="text" id="num2" placeholder="请输入数值"/>
<input type="button" value="点击计算" onclick="calculate()"/><br>
<hr>
结果=<span id="result"></span>
<script>
function calculate(){
//获取输入框的内容
var num1 =document.getElementById("num1").value;
var opt =document.getElementById("opt").value;
var num2 =document.getElementById("num2").value;
//判断输入是否为数字
if(isNaN(num1)||isNaN(num2)){
alert("请输入数字");
return ;
}
//把字符串类型的数字转换成数字类型的数字
num1=Number(num1);
num2=Number(num2);
var result=0;
switch (opt){
case"+":
result=num1+num2;
break;
case"-":
result=num1-num2;
break;
case"*":
result=num1*num2;
break;
case"/":
//判断除数是否为0
if(num2==0){
alert("除数不能为0");
}else {
result=num1/num2;
}
break;
default:
result=0
}
//结果显示
result=result.toFixed(3);//结果小数点后保留三位
document.getElementById("result").innerText=result;
}
</script>
</body>
</html>