本文实例为大家分享了JavaScript实现简易计算器的具体代码,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >计算器</ title >
</ head >
< body >
<!--页面布局-->
< input type = "text" id = "num1" placeholder = "请输入第一个数字" />
< input type = "text" id = "operator" placeholder = "请输入运算符" >
< input type = "text" id = "num2" placeholder = "请输入第二个数字" />
< input type = "button" onclick = "count()" value = "计算" />< br />
< span >计算结果:</ span >< span id = "result" ></ span >
<!--JavaScript-->
< script >
function count() {
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var operator = document.getElementById("operator").value;
var num = "";
//判断输入的两个数字是否为数字,如果为数字,返回结果为false
var num1 = parseFloat(num1);
var num2 = parseFloat(num2);
var isNotNumber = isNaN(num1) || isNaN(num2);
if (!isNotNumber) {
switch (operator) {
case "+":
num = num1 + num2;
break;
case "-":
num = num1 - num2;
break;
case "*":
num = num1 * num2;
break;
case "/":
if (num2 == 0) {
// 除数不能为0
alert("除数不能为0");
} else {
num = num1 / num2;
break;
}
default:
alert("请输入正确的运算符!!!");
}
num = num.toFixed(2);
document.getElementById("result").innerText = num;
} else {
alert("请输入数字!!!")
}
}
</ script >
</ body >
</ html >
|
运行效果:
测试结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/m0_49926319/article/details/109191657