javascript计算器报告附源代码
javascript实现简易计算器的代码_
javascript实现简易计算器的代码_ 下面我就为大家带来一篇javascript实现简易计算器的代码我觉得挺不错的,现在分享给大家,也给大家做个参考。
今日闲来无聊,想写点什么,突然想到用javascript写一个计算器。
程序还存在许多的Bug,先在这里记录一下,以后慢慢更正。
代码如下:!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "l1/DTD/xhtml1-transitional.dtd" html xmlns="l"headmeta http-equiv="Content-Type" content="text/html; charset=utf-8" /titlejavascript实现简易计算器的代码_脚本之家/titlestyle type="text/css"input{width:30px;height:20px;text-align:center;}#tbCalculator td{text-align:center;vertical-align:middle;}/stylescript type="text/javascript"var result; //保存点击运算符之前输入框中的数值var operator; //保存运算符var isPressEqualsKey = false; //记录是否按下”=“键 //数字键大事function connectionDigital(control){var txt = document.getElementById('txtScream'); if(isPressEqualsKey){txt.value = ""; //已进行过计算,则清空数值输入框重新开头isPressEqualsKey = false;}//数值输入已经存在小数点,则不允许再输入小数点if(txt.value.indexOf('.') -1 control.value == '.')return false;txt.value += control.value; //将控件值赋给数值输入框中}//退格键大事function backspace(){var txt = document.getElementById('txtScream'); txt.value = txt.value.substring(0,txt.value.length - 1);}//ce键大事:清空数字输入框function clearAll(){document.getElementById('txtScream').value = ""; result = "";operator = "";}// +、-、*、/ 大事function calculation(control){//将运算符保存入全局变量中operator = control.value;var txt = document.getElementById('txtScream'); if(txt.value == "")return false; //数值输入框中没有数字,则不能输入运算符//将数值输入框中的值保存到计算表达式中result = txt.value;//清空输入框,以待输入操作值txt.value = "";}//计算结果function getResult(){var opValue;//计算表达式中存在运算符var sourseValue = parseFloat(result);var txt = document.getElementById('txtScream'); if(operator == '*')opValue = sourseValue * parseFloat(txt.value); else if(operator == '/')opValue = sourseValue / parseFloat(txt.value);else if(operator == '+')opValue = sourseValue + parseFloat(txt.value);else if(operator == '-')opValue = sourseValue - parseFloat(txt.value);txt.value = opValue;isPressEqualsKey = true;result = "";opValue = "";}/script/headbodytable id="tbCalculator" width="200" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#0066FF"trtd height="30" colspan="4" align="center"input type="text" name="txtScream" id="txtScream" style="width:180px; border-style:none; text-align:right;" readonly="readonly" / /td/trtrtd height="30" colspan="2"input type="button" name="btnCE" id="btnCE" value="C E" style="width:80px;" align="right"; onclick="clearAll();" //tdtd height="30" colspan="2"input type="button" name="btn10" id="btn10" value="Backspace" style="width:80px;" align="right"; onclick="backspace();" //td/trtrtd height="30"input type="button" name="btn7" id="btn7" value="7" onclick="connectionDigital(this);" //tdtdinput type="button" name="btn8" id="btn8" value="8" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn9" id="btn9" value="9" onclick="connectionDigital(this);" //td tdinput type="button" name="btn6" id="btn6" value="/" onclick="calculation(this);" //td/trtrtd height="30"input type="button" name="btn4" id="btn4" value="4" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn5" id="btn5" value="5" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn6" id="btn6" value="6" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn13" id="btn13" value="*" onclick="calculation(this);" //td/trtrtd height="30"input type="button" name="btn1" id="btn1" value="1" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn2" id="btn2" value="2" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn3" id="btn3" value="3" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn18" id="btn18" value="-" onclick="calculation(this);" //td/trtrtd height="30"input type="button" name="btn0"id="btn0" value="0" onclick="connectionDigital(this);"//tdtdinput type="button" name="btndot" id="btndot" value="." onclick="connectionDigital(this);" //td tdinput name="btn22" type="button" id="btn22" value="=" onclick="getResult();" //tdtdinput type="button" name="btn23" id="btn23" value="+" onclick="calculation(this);" //td/tr/table/body/html以上这篇javascript实现简易计算器的代码就是我分享给大家的全部内容了,盼望能给大家一个参考...。
javascript代码实现简易计算器
javascript代码实现简易计算器本⽂实例为⼤家分享了javascript实现简易计算器的具体代码,供⼤家参考,具体内容如下编辑了⼏个⼩时研发了⼀个简易好理解的计算器。
不停改Bug,终于改好了。
这是样式这是Css部分<style>#box {background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);width: 500px;height: 420px;margin: auto;margin-top: 200px;position: relative;}.reckon {width: 280px;height: 200px;background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);;position: absolute;top: 100px;left: 100px;border: 5px solid #2a2b2c}#input1 {background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);border: none;width: 220px;height: 8px;float: right;margin-top: 10px;margin-right: 20px;outline: none;padding: 10px}ul li {float: left;list-style: none;margin: 4px 2px;border-radius: 3px;background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);box-shadow: 2px 2px #ccc;color: #fff;font-weight: "楷体";width: 50px;height: 30px;text-align: center;line-height: 30px;}ul {margin-top: 5px;}ul li:hover {opacity: 0.7;}</style>这是HTML部分<div id="box"><div class="reckon" id="reckon"><input type="text" id="input1"><ul><li class="num">7</li><li class="num">8</li><li class="num">9</li><li class="opcr">+</li><li class="num">4</li><li class="num">5</li><li class="num">6</li><li class="opcr">- </li><li class="num">1</li><li class="num">2</li><li class="num">3</li><li class="opcr">*</li><li class="num">0</li><li id="returnZero">C</li><li id="resule">=</li><li class="opcr">/</li></ul></div></div>/* 定义两个标签来存放符号跟第⼀个值*/<input type="text" id="text1" style="display:none"><input type="text" id="per" style="display:none">html部分的话就是吧所有数字定义为⼀个class名字,把所有运算符号定义为⼀个class 以及定义两个input来存放运算符<script>lis = document.querySelectorAll("#box ul .num")//获取所有的数字opcr = document.querySelectorAll("#box ul .opcr")//获取运算符for (var i = 0; i < lis.length; i++) { //遍历所有的数字lis[i].onclick = function () {input1.value += parseInt(this.innerHTML)//点击input1显⽰}}//遍历所有的运算符for (let i = 0; i < opcr.length; i++) {opcr[i].onclick = function () {if (text1.value == "") {//当存放第⼀个值为空时候text1.value = input1.value//存放第⼀个值input1.value = "" //input框⾥的值为空per.value = this.innerHTML; //存放符号的值为空} else {text1.value = eval(text1.value + per.value + input1.value)//不是空的时候计算per.value = this.innerHTML;//存放符号的值为点击的值input1.value = ""//input框⾥的值为空}}}//等于resule.onclick = function () {input1.value = eval(text1.value + per.value + input1.value)//计算⾥⾯的值 per.value = "" //清空存放per的值text1.value = ""//input框⾥的值为空}//点击清空所有returnZero.onclick = function () {input1.value = ""per.value = ""text1.value = ""}</script>完整部分<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"><title>简易计算器</title><style>#box {background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%); width: 500px;height: 420px;margin: auto;margin-top: 200px;position: relative;}.reckon {width: 280px;height: 200px;background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%); ;position: absolute;top: 100px;left: 100px;border: 5px solid #2a2b2c}#input1 {background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);border: none;width: 220px;height: 8px;float: right;margin-top: 10px;margin-right: 20px;outline: none;padding: 10px}ul li {float: left;list-style: none;margin: 4px 2px;border-radius: 3px;background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%); box-shadow: 2px 2px #ccc;color: #fff;font-weight: "楷体";width: 50px;height: 30px;text-align: center;line-height: 30px;}ul {margin-top: 5px;}opacity: 0.7;}</style></head><body><div id="box"><div class="reckon" id="reckon"><input type="text" id="input1"><ul><li class="num">7</li><li class="num">8</li><li class="num">9</li><li class="opcr">+</li><li class="num">4</li><li class="num">5</li><li class="num">6</li><li class="opcr">- </li><li class="num">1</li><li class="num">2</li><li class="num">3</li><li class="opcr">*</li><li class="num">0</li><li id="returnZero">C</li><li id="resule">=</li><li class="opcr">/</li></ul></div></div><input type="text" id="text1" style="display:block"><input type="text" id="per" style="display:block"><script>lis = document.querySelectorAll("#box ul .num")//获取所有的数字opcr = document.querySelectorAll("#box ul .opcr")//获取+——*/for (var i = 0; i < lis.length; i++) { //遍历所有的数字lis[i].onclick = function () {input1.value += parseInt(this.innerHTML)//点击input1显⽰}}//遍历所有的+——*/for (let i = 0; i < opcr.length; i++) {opcr[i].onclick = function () {if (text1.value == "") {//当存放第⼀个值为空时候text1.value = input1.value//存放第⼀个值input1.value = "" //input框⾥的值为空per.value = this.innerHTML; //存放符号的值为空} else {text1.value = eval(text1.value + per.value + input1.value)//不是空的时候计算值 per.value = this.innerHTML;//存放符号的值为点击的值input1.value = ""//input框⾥的值为空}}}//等于resule.onclick = function () {input1.value = eval(text1.value + per.value + input1.value)//计算⾥⾯的值per.value = "" //清空存放per的值text1.value = ""//input框⾥的值为空}//点击清空所有returnZero.onclick = function () {input1.value = ""per.value = ""text1.value = ""}</script></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JavaScript计算器网页版实现代码分享
JavaScript计算器⽹页版实现代码分享JavaScript⽹页计算器代码,该计算器是⽤DW写的!HTML篇<html<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>计算器</title><link href="style/calculator.css" rel="stylesheet" type="text/css" /><script src="JavaScript/calculator.js"></script>></head><body ><form id="form1" name="form1" method="post" action=""><table width="320" border="1" cellpadding="0" cellspacing="0" class="trb" id="calculator"><tr><td height="100" colspan="4" align="left" valign="top"><label for="txt"></label><input name="txt" type="text" class="txt" id="txt" value="0" onfocus="this.blur();"/></td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="deleteAll();">C</td><td width="80" height="40" align="center" valign="middle" onclick="Backspace();">←</td><td width="80" height="40" align="center" valign="middle" onclick="sign();">±</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="add();">+</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(7);">7</td><td width="80" height="40" align="center" valign="middle" onclick="command(8);">8</td><td width="80" height="40" align="center" valign="middle" onclick="command(9);">9</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="subtract();">-</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(4);">4</td><td width="80" height="40" align="center" valign="middle" onclick="command(5);">5</td><td width="80" height="40" align="center" valign="middle" onclick="command(6);">6</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="multiply();">×</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(1);">1</td><td width="80" height="40" align="center" valign="middle" onclick="command(2);">2</td><td width="80" height="40" align="center" valign="middle" onclick="command(3);">3</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="divide();">÷</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(0);">0</td><td width="80" height="40" align="center" valign="middle" onclick="dot();">▪</td><td height="40" colspan="2" align="center" valign="middle" bgcolor="#CC6600" onclick="equal();">=</td></tr></table><p> </p><p> </p></form></body></html>CSS篇@charset "utf-8";/* CSS Document */.trb {font-family: Georgia, "Times New Roman", Times, serif;font-size: 24px;color: #FFF;background-color: #333;text-align: center;border: 1px solid #999;}.operator {background-color: #333;font-size: 18px;font-family: Verdana, Geneva, sans-serif;}td:hover{font-size: 28px;cursor:pointer;}.txt {height: 100px;width: 320px;background-color: #333;text-align: left;vertical-align: bottom;color: #FFF;font-size: 30px;}JavaScript篇//实现计算器功能//结果var result = 0;//显⽰框中的数(默认为“0”)var screenNum = "0";//数的初始输⼊状态,默认为0;当按了任意运算符键后,数的输⼊状态变为1var state = 0;//防⽌重复按运算符键var avoidRepeat = true;//运算符键(默认为0--等于号)var operator = 0;//第⼀步:获取按键值,并显⽰在显⽰框中function command(num) {//获取显⽰框的值var str = String(document.form1.txt.value);//对该值进⾏判断,如果该值不为"0",且输⼊状态0,则返回前者,否则为""(双重三⽬运算) //两个判断条件:1、显⽰框中值是否为"0", 2、数的输⼊状态str = (str != "0")?((state == 0)?str:""):"";//给当前值追加字符str = str + String(num);//刷新显⽰document.form1.txt.value = str;//按了任意数字键后,数的输⼊状态变为0state = 0;//重置防⽌重复按键avoidRepeat = true;}//第⼆步:确保输⼊的数是合法的,每个数⾄多只有⼀个⼩数点function dot() {var str = String(document.form1.txt.value);//若该数前⾯未接运算符,则返回前值,否则为"0";str = (state == 0)?str:"0";//Java⾥String有length()⽅法,⽽JS⾥String有length属性for(i=0;i<=str.length;i++) {//substr()获取下标从i开始,个数为1个的⼦串if(str.substr(i,1)==".") {//当存在⼩数点时,则程序终⽌return;}}//若⽆⼩数点,则在该数后⾯加上str = str+".";//刷新显⽰document.form1.txt.value = str;//恢复数的初始输⼊状态state = 0;}//第三步:处理退格键function Backspace() {var str= String(document.form1.txt.value);//若显⽰框中数不等于"0",则返回str,否则返回""str = (str != "0")?str:"";str = str.substr(0,str.length-1);//若str不为"",则返回⼦串str,否则str="0" str = (str != "")?str:"0";//刷新显⽰document.form1.txt.value = str;}//第四步:删除所有function deleteAll() {//显⽰框设为"0"document.form1.txt.value = "0";//恢复数的初始输⼊状态state = 0;//恢复运算符键,默认为0--等于号operator = 0;}//第五步:加法function add() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//更改运算符键,1--加号operator = 1;}//第六步:减法function subtract() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//2--减号operator = 2;}//第七步:乘法function multiply() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//3--乘号operator = 3;}//第⼋步:除法function divide() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//4--除号operator = 4;}//第九步:正负号function sign() {//5--正负号operator = 5;//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//0--等于号operator = 0;//正负号可以连续按avoidRepeat = true;}//第⼗步:等于function equal() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//0--等于号operator = 0;}//第⼗⼀步:计算function calculate() {//获取显⽰框中的值screenNum = Number(document.form1.txt.value);if(avoidRepeat) {switch(operator){case 1:result = result + screenNum;document.form1.txt.value = result;break;case 2:result = result - screenNum;document.form1.txt.value = result;break;case 3:result = result * screenNum;document.form1.txt.value = result;break;case 4:if(screenNum == 0){//设置显⽰框的值document.getElementById("txt").value="除数不能为0";//3s后,执⾏清屏函数setTimeout(clearScreen,3000);}else{result = result/screenNum;document.form1.txt.value = result;}break;case 5:result = (-1)*screenNum;document.form1.txt.value = result;break;case 0:result = screenNum;document.form1.txt.value = result;break;}//当按了运算符键后,不能再按avoidRepeat = false;}}//第⼗⼆步:清屏函数function clearScreen() {document.getElementById("txt").value = "0";}关于计算器的精彩⽂章请查看,更多精彩等你来发现!以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
Javascript实现简单计算器实例代码
Javascript实现简单计算器实例代码效果图:刚开始做时没考虑到清零和退格两个功能,嘻嘻,后来加的整体与传统计算器⽐有点⼩瑕疵。
代码:<!DOCTYPE html><html><head><meta charset="utf-8"><title>js简单计算器</title><style type="text/css">*{margin:0px;padding:0px;}input{margin-top:2px;margin-left:2px;width:230px;height:30px;text-align:right;}button{margin-top:2px;margin-left:2px;width:50px;height:50px;}#container{margin-left:1px;border:1px solid #E4E4E4;background:#BBBBBB;width:235px;height:215px;}</style><script>function onLoad(){//加载完毕后光标⾃动对应到输⼊框document.getElementById("input").focus();}//读取按钮的值,传给输⼊框function inputEvent(e){//把val的值改为每个事件的innerHTML值var val=e.innerHTML;//获取input标签var xsval=document.getElementById("input");//标签⾥的value连接每个事件的innerHTML值xsval.value+=val;}//计算出结果function inputOper(){var xsval=document.getElementById("input");xsval.value=eval(document.getElementById("input").value);}//清零function clearNum(){var xsval=document.getElementById("input");xsval.value="";document.getElementById("input").focus();}//退格function backNum(){var arr=document.getElementById("input");arr.value=arr.value.substring(0,arr.value.length-1);}</script></head><body onload="onLoad()"><input id="input" type="text"><div id="container"><div><button onclick="inputEvent(this)">1</button><button onclick="inputEvent(this)">2</button><button onclick="inputEvent(this)">3</button><button onclick="inputEvent(this)">+</button></div><div><button onclick="inputEvent(this)">4</button><button onclick="inputEvent(this)">5</button><button onclick="inputEvent(this)">6</button><button onclick="inputEvent(this)">-</button></div><div><button onclick="inputEvent(this)">7</button><button onclick="inputEvent(this)">8</button><button onclick="inputEvent(this)">9</button><button onclick="inputEvent(this)">*</button></div><div><button onclick="inputEvent(this)">0</button><button onclick="inputEvent(this)">.</button><button onclick="inputOper(this)">=</button><button onclick="inputEvent(this)">/</button></div></div><button onclick="clearNum()">清零</button><button onclick="backNum()">退格</button></body></html>感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!。
简易计算器js代码
<li onclick="getNum(2)">2</li>
<li onclick="getNum(3)">3</li>
<li onclick="getFh('*')">*</li>
<li onclick="getFh('/')">/</li>
<li class="li3" onclick="getNum(0)">0</li>
<li onclick="">.</li>
<li class="li3" onclick="jisuanqi()">=</li>
</ul>
</div>
</div>
<script type="text/javascript">
}
oinp.value =result; //将结果输入oinp.value上
}
function getClean()
{
oinp.value= 0;//清除oinp.value值
}
function getDel()
{
var temp;//先定义一个变量
temp = oinp.value.substr(0,oinp.value.length-1);//将字符串的最后一个字符截取出去,剩下的字符串保存到temp;
JavaScript实现简单的四则运算计算器完整实例
JavaScript实现简单的四则运算计算器完整实例本⽂实例讲述了JavaScript实现简单的四则运算计算器。
分享给⼤家供⼤家参考,具体如下:运⾏效果图如下:完整实例代码如下:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>computer</title><script>function compute(){str1=Number(document.getElementById("txt1").value);str2=Number(document.getElementById("txt2").value);comp=document.getElementById("select").value;var result;switch(comp) {case "+":comp=str1+str2;break;case "-":comp=str1-str2;break;case "*":comp=str1*str2;break;case "/":if(str2==0){alert("除数不能为0!");comp='';}else{comp=str1/str2;}break;}document.getElementById("result").value=comp;}</script></head><body><input type="text" id="txt1"/><select name="method" id="select"><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option></select><input type="text" id="txt2"/><input type="button" id="b1" value="等于" onclick="compute()" /><input type="text" id="result"/></body></html>PS:这⾥再为⼤家推荐⼏款计算⼯具供⼤家进⼀步参考借鉴:更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家JavaScript程序设计有所帮助。
js中简单计算器的代码
js中简单计算器的代码在JavaScript中,我们可以使用简单的语法来编写一个基本的计算器。
计算器可以执行加法、减法、乘法和除法等数学运算操作。
为了编写这个计算器程序,我们需要创建三个主要的函数,分别是获取输入、执行计算和输出结果。
首先定义一个由用户输入的数字和运算符组成的表达式,然后解析表达式,并在最终屏幕上显示计算结果。
下面是一个简单的计算器程序示例,可以执行加法、减法、乘法和除法四种基本运算:```jsfunction getInputValue() {var x = parseFloat(document.getElementById("input1").value); var y = parseFloat(document.getElementById("input2").value); var op = document.getElementById("operator").value;return [x, y, op];}function calculate() {var result;var [x,y,op] = getInputValue();if (op === "+") {result = x + y;} else if (op === "-") {result = x - y;} else if (op === "*") {result = x * y;} else if (op === "/") {result = x / y;}return result;}function displayResult() {var result = calculate();document.getElementById("result").innerHTML = result;}```这个计算器程序中,`getInputValue()`函数获取用户输入的数值和运算符,`calculate()`函数执行数学运算并返回计算结果,`displayResult()`函数将结果输出到屏幕上。
js写的计算器代码
{ Form1.result.value="";}
last=panduan;
Form1.result.value=Form1.result.value+panduan;
}
if(panduan==5)
{ if(last=="+")
}
function clear()
{alert("asdf");
Form1.result1.value="";
Form1.result2.value="";
Form1.result3.value="";
}
function qingchu()
{
}
if(panduan==0)
{ if(last=="+")
{ Form1.result.value="";}
if(last=="-")
{ Form1.result.value="";}
if(last=="*")
{ Form1.result.value="";}
last=panduan ;
Form1.result.value=Form1.result.value+panduan;
}
if(panduan==6)
{ if(last=="+")
{ Form1.result.value="";}
JavaScript实现简单的计算器功能
JavaScript实现简单的计算器功能本⽂实例为⼤家分享了JavaScript实现简单计算器功能的具体代码,供⼤家参考,具体内容如下具体要求如下:实现代码:<html><head><meta charset="utf-8"><title>计算器</title><script>function myck(type){var num1 = document.getElementById("num1");var num2 = document.getElementById("num2");if(type==1){// 计算操作var result = parseInt(num1.value) + parseInt(num2.value);alert(result);document.getElementById("resultDiv").innerText ="最终计算结果:"+ result;}else if(type==2){var result = parseInt(num1.value) - parseInt(num2.value);alert(result);document.getElementById("resultDiv").innerText ="最终计算结果:"+ result;}else if(type==3){var result = parseInt(num1.value) * parseInt(num2.value);alert(result);document.getElementById("resultDiv").innerText ="最终计算结果:"+ result;}else if(type==4){if(confirm("是否正确清空?")){// 清空num1.value = "";num2.value = "";document.getElementById("resultDiv").innerText="";}}}</script></head><body><div style="margin-top: 100px;margin-left: 500px;"><span style="font-size: 60px;">计算器</span></div><div><div class="innerDiv" style="margin-left: 490px;">数 字1:<input id="num1" type="number" placeholder="请输⼊数字1"></div></div><div><div class="innerDiv" style="margin-left:490px;">数 字2:<input id="num2" type="number" placeholder="请输⼊数字2"></div></div><div><div style="margin-left: 500px;" class="innerDiv"><input type="button" onclick="myck(1)" value="相 加"><input type="button" onclick="myck(2)" value="相 减"><input type="button" onclick="myck(3)" value="相 乘"><input type="button" onclick="myck(4)" value="清 空"></div></div><div id="resultDiv"></div></body><style>.innerDiv{margin-left: 420px;margin-top: 20px;}</style></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JS制作简易计算器的实例代码
JS制作简易计算器的实例代码做⼀个简易计算器,效果图⽚c表⽰清空,为⼀个空字符串+/-表⽰该值为正还是负%表⽰当前值/100←表⽰退格,往前删除⼀个值eval 函数是能够计算出字符串表达式或者语句的结果,把结果求出来。
代码如下<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">#div1{margin:20px auto;width:420px;height:490px;background-color:#E8E8E8;border:1px solid #ccc;border-radius:5px;}.div2{width:410px;height:60px;border:1px solid #ccc;margin:5px auto;border-radius:5px;text-align:right;font-size:30px;background-color:white;padding-top:10px;}.div3{width:410px;height:60px;margin:5px auto;float:left;}.div13{float:left;width:70px;height:60px;border:1px solid #ccc;background-color: ghostwhite;margin-left:8px;text-align:center;font-size:30px;color:deepskyblue;border-radius:5px;cursor:default;padding-top:10px;box-shadow:4px 3px 3px #CCCCCC;}.div133{width:160px;}.top{margin-top:10px;margin-left:10px;}.color{color:black;}.top1{margin-top:20px;margin-left:10px;}.top2{margin-top:30px;margin-left:10px;}.top3{margin-top:40px ;margin-left:10px;}.div23{float:left;}.div33{float:left;}</style><div id="div1"><div class="div2" id="input"><b>0</b></div><div class="div3"><div class="div13" onclick="w(' ')"><b>C</b></div><div class="div13"onclick="w('opposite')"><b>+/-</b></div><div class="div13" onclick="w('percent')"><b>%</b></div><div class="div13 div133" onclick="w('backspace')"><b>←</b></div></div><div class="div3"><div class="div13 top color" onclick="a('7')"><b>7</b></div><div class="div13 top color" onclick="a('8')"><b>8</b></div><div class="div13 top color" onclick="a('9')"><b>9</b></div><div class="div13 top " onclick="a('+')"><b>+</b></div><div class="div13 top " onclick="a('-')"><b>-</b></div></div><div class="div3"><div class="div13 top1 color" onclick="a('4')"><b>4</b></div><div class="div13 top1 color"onclick="a('5')"><b>5</b></div><div class="div13 top1 color" onclick="a('6')"><b>6</b></div><div class="div13 top1" onclick="a('*')"><b>×</b></div><div class="div13 top1" onclick="a('/')"><b>÷</b></div></div><div class="div3"><div class="div13 top2 color" onclick="a('1')"><b>1</b></div><div class="div13 top2 color" onclick="a('2')"><b>2</b></div><div class="div13 top2 color"onclick="a('3')"><b>3</b></div><div class="div13 top2"onclick="w('pow')"><b>x<sup>2</sup></b></div><div class="div13 top2" onclick="w('sqrt')"><b>√</b></div></div><div class="div3"><div class="div13 top3 color" onclick="a('0')"><b>0</b></div><div class="div13 top3"onclick="a('.')"><b>.</b></div><div class="div13 top3"onclick="e('=')"><b>=</b></div></div></div><script>input=document.getElementById("input");s="";function a(v){s=s+v;input.innerHTML=s;}function e(v){input.innerHTML=eval(s);}function w(type){switch(type){ case ' ':s='';break;case 'opposite':s=-s;break;case 'percent':s=s/100;break;case 'pow':s=Math.pow(s,2);break;case 'sqrt':s=Math.sqrt(s);break;case 'backspace':s=s.substr(s,s.length-1);// case 'backspace':s=s.substring(0,s.length-1); }input.innerHTML=s;}</script>这⾥我本来是采⽤的substring这个函数的,但是在计算的时候,当只留下⼀个值的时候,按←的时候就不起作⽤,但是把substring改成substr的时候就能清除的了,原因我觉得应该是这样:s=s.substring(s,s.length-1);当只剩下⼀个值的时候,假设s 值为7,substring中的第⼀个参数为是,表⽰中国字符串的⾸地址,就是0,第⼆个参数为0,怎么取,但是换成这样是可以的s=s.substring(0,s.length-1);,但是⽤s=s.substr(s,s.length-1);当只剩下⼀个值的时候是可以清除掉的,我想应该是当第⼆个参数是取得个数为0的时候,就把空字符串赋给s了吧。
JS计算器代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><style type="text/css">*{font-size:12px;}#table1 {width: 260px;cellspacing: 0;cellpadding: 0;}#table2{width:258px;cellspacing:0px;cellpadding:0px;}#table3{width: 246px;border: 0px;cellspacing: 2px;cellpadding: 0px;margin-left:6px;}#num {text-align:right;margin-left:7px;}.zi{font-size:13px;color:#FFFFFF;font-weight:bold;}.niu1{width:38px;color:#0000FF;}.niu2{width:38px;color:#FF0000;}.niu3{width:35px;color:#FF0000;}#play{text-align:center;width:22px;background:#ECE9D8}</style><script>var num1=null,num2=null,opr; //num1,num2分别用来存放运算符号前、后的两个数var operator=null,bool=true;//输入数字0-9---------------------------------------function fun1(number){if (bool_1){num.value="";bool_1=false;}if(num.value=="0"){num.value=number;}else{num.value=num.value+number;}if (bool) //当输入了“=”,接着又输入数值时{num1=null;num2=null; //将num1,num2的值还原为空值bool=false; //将这种功能关闭}} var bool_1=false,bool_2=true,bool_3=true;//输入运算符号-------------------------------------function fun8(x){num1=num.value;if (num2==null){num2=num1}else{num2=fun12(num2,operator,num1)num.value=num2}operator=x; //operator包含+、-、*、/等运算符号num.value="";bool=false;}//等号=----------------------------------------------function fun11(){if (operator!=null){if (bool_2){num1=num.value;bool_2=false}num2=fun12(num1,operator,num2);num.value=num2bool=true;bool_1=true;}}//运算+、-、*、/的过程--------------------------------------------function fun12(temp1,opr,temp2){if (opr=="/"&&temp2=="0"){return "除数不能为零。
javascript制作计算器源代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="description" content="javascript计算器,由梅强强制作" /> <title>计算器</title><script type="text/javascript">alert("本计算器由梅强强制作QQ:826219395");function getResult(type){if(checkData()){}var no1=parseInt(document.jisuanqi.no1.value);var no2=parseInt(document.jisuanqi.no2.value);var result;switch(type){case '+':result = no1+no2;break;case '-':result =no1-no2;break;case '*':result =no1*no2;break;case '/':result =no1/no2;break;case '%':result =no1%no2;break;}document.jisuanqi.result.value=result;}function checkData(){if(document.jisuanqi.no1.value==""){alert("第一个数字不能为空!请重新输入");return;}if(document.jisuanqi.no2.value==""){alert("第二个不能为空!请重新输入");return;}if(document.jisuanqi.no1.value=="0"){alert("第一个不能为零!请重新输入");return;}if(isNaN(document.jisuanqi.no1.value)){alert("第一个不是数字!请重新输入");return;}if(isNaN(document.jisuanqi.no2.value)){alert("第二个不是数字!请重新输入");}}</script></head><body><font size="6" color="#000000">本计算器由梅强强制作<br>QQ:826219395</font><p align="center" /><form name="jisuanqi">no1:<input name="no1" /><br>no2:<input name="no2" /><br>result:<input name="result" /><br><input type="button" value="+" onclick="getResult('+')" /> <input type="button" value="-" onclick="getResult('-')" /> <input type="button" value="*" onclick="getResult('*')" /> <input type="button" value="/" onclick="getResult('/')" /><input type="button" value="%" onclick="getResult('%')" /></form></p></body></html>。
简单的计算器源代码
//计算器,已经编译通过import java.awt.*;import java.awt.event.*;import javax.swing.*;public class testZ extends JFrame implements ActionListener{private JPanel jPanel1,jPanel2;private JTextField resultField;private JButton s1,s2,s3,s4,s5,s6,s7,s8,s9,s0,b1,b2,b3,b4,f1,f2; private boolean end,add,sub,mul,div;private String str;private double num1,num2;public testZ(){super("计算器");setSize(300,240);Container con=getContentPane();con.setLayout(new BorderLayout());jPanel1=new JPanel();jPanel1.setLayout(new GridLayout(1,1));jPanel2=new JPanel();jPanel2.setLayout(new GridLayout(4,4));resultField=new JTextField("0");jPanel1.add(resultField);con.add(jPanel1,BorderLayout.NORTH);s1=new JButton(" 1 "); s1.addActionListener(this);s2=new JButton(" 2 "); s2.addActionListener(this);s3=new JButton(" 3 "); s3.addActionListener(this);s4=new JButton(" 4 "); s4.addActionListener(this);s5=new JButton(" 5 "); s5.addActionListener(this);s6=new JButton(" 6 "); s6.addActionListener(this);s7=new JButton(" 7 "); s7.addActionListener(this);s8=new JButton(" 8 "); s8.addActionListener(this);s9=new JButton(" 9 "); s9.addActionListener(this);s0=new JButton(" 0 "); s0.addActionListener(this);b1=new JButton(" + "); b1.addActionListener(this);b2=new JButton(" - "); b2.addActionListener(this);b3=new JButton(" * "); b3.addActionListener(this);b4=new JButton(" / "); b4.addActionListener(this);f1=new JButton(" . "); f1.addActionListener(this);f2=new JButton(" = "); f2.addActionListener(this);jPanel2.add(s1);jPanel2.add(s2);jPanel2.add(s3);jPanel2.add(b1);jPanel2.add(s4);jPanel2.add(s5);jPanel2.add(s6);jPanel2.add(b2);jPanel2.add(s7);jPanel2.add(s8);jPanel2.add(s9);jPanel2.add(b3);jPanel2.add(s0);jPanel2.add(f1);jPanel2.add(f2);jPanel2.add(b4);con.add(jPanel2,BorderLayout.CENTER);}public void num(int i){String s = null;s=String.valueOf(i);if(end){//如果数字输入结束,则将文本框置零,重新输入resultField.setText("0");end=false;}if((resultField.getText()).equals("0")){//如果文本框的内容为零,则覆盖文本框的内容resultField.setText(s);}else{//如果文本框的内容不为零,则在内容后面添加数字str = resultField.getText() + s;resultField.setText(str);}}public void actionPerformed(ActionEvent e){ //数字事件 if(e.getSource()==s1)num(1);else if(e.getSource()==s2)num(2);else if(e.getSource()==s3)num(3);else if(e.getSource()==s4)num(4);else if(e.getSource()==s5)num(5);else if(e.getSource()==s6)num(6);else if(e.getSource()==s7)num(7);else if(e.getSource()==s8)num(8);else if(e.getSource()==s9)num(9);else if(e.getSource()==s0)num(0);//符号事件else if(e.getSource()==b1)sign(1);else if(e.getSource()==b2)sign(2);else if(e.getSource()==b3)sign(3);else if(e.getSource()==b4)sign(4);//等号else if(e.getSource()==f1){str=resultField.getText();if(str.indexOf(".")<=1){str+=".";resultField.setText(str);}}else if(e.getSource()==f2){num2=Double.parseDouble(resultField.getText());if(add){num1=num1 + num2;}else if(sub){num1=num1 - num2;}else if(mul){num1=num1 * num2;}else if(div){num1=num1 / num2;}resultField.setText(String.valueOf(num1));end=true;}}public void sign(int s){if(s==1){add=true;sub=false;mul=false;div=false;}else if(s==2){add=false;sub=true;mul=false;div=false;}else if(s==3){add=false;sub=false;mul=true;div=false;}else if(s==4){add=false;sub=false;mul=false;div=true;}num1=Double.parseDouble(resultField.getText()); end=true;}public static void main(String[] args){testZ th1=new testZ();th1.show();}}。
js中简单计算器的代码
js中简单计算器的代码下面是一个简单的JavaScript计算器代码,可以进行加、减、乘、除四种基本运算:```javascript// 获取操作数和运算符的元素var num1 = document.getElementById('num1');var num2 = document.getElementById('num2');var operator = document.getElementById('operator');// 获取结果元素var result = document.getElementById('result');// 定义计算函数function calculate() {var n1 = parseFloat(num1.value); // 将字符串转换为数字 var n2 = parseFloat(num2.value);var op = operator.value;var res;// 根据运算符进行计算switch(op) {case '+':res = n1 + n2;break;case '-':res = n1 - n2;break;case '*':res = n1 * n2;break;case '/':res = n1 / n2;break;default:res = 0;}// 将结果显示在页面上result.innerHTML = res;}// 绑定计算按钮的点击事件var btn = document.getElementById('calculate');btn.onclick = calculate;```以上代码中,我们通过 `getElementById` 方法获取了操作数和运算符的输入元素,并通过 `onclick` 事件绑定了计算按钮的点击事件。
js计算器源代码
<HTML><HEAD><TITLE></TITLE><style type="text/css">p {font-size: 12pt}.red {color: red;width:34}.redl{color:red;width:51}.blue {color: blue;width:34}</style><SCRIPT LANGUAGE="JavaScript">var Memory = 0;var Number1 = "";var Number2 = "";var NewNumber = "blank";var opvalue = "";function Display(displaynumber) {document.calculator.answer.value = displaynumber; }function MemoryClear() {Memory = 0;document.calculator.mem.value = "";}function MemoryRecall(answer) {if(NewNumber != "blank") {Number2 += answer;} else {Number1 = answer;}NewNumber = "blank";Display(answer);}function MemorySubtract(answer) {Memory = Memory - eval(answer);}function MemoryAdd(answer) {Memory = Memory + eval(answer); document.calculator.mem.value = " M "; NewNumber = "blank";}function ClearCalc() {Number1 = "";Number2 = "";NewNumber = "blank";Display("");}function Backspace(answer) { answerlength = answer.length;answer = answer.substring(0, answerlength - 1); if (Number2 != "") {Number2 = answer.toString();Display(Number2);} else {Number1 = answer.toString();Display(Number1);}}function CECalc() {Number2 = "";NewNumber = "yes";Display("");}function CheckNumber(answer) {if(answer == ".") {Number = document.calculator.answer.value; if(Number.indexOf(".") != -1) {answer = "";}}if(NewNumber == "yes") {Number2 += answer;Display(Number2);}else {if(NewNumber == "blank") {Number1 = answer;Number2 = "";NewNumber = "no";}else {Number1 += answer;}Display(Number1);}}function AddButton(x) {if(x == 1) EqualButton();if(Number2 != "") {Number1 = parseFloat(Number1) + parseFloat(Number2); }NewNumber = "yes";opvalue = '+';Display(Number1);}function SubButton(x) {if(x == 1) EqualButton();if(Number2 != "") {Number1 = parseFloat(Number1) - parseFloat(Number2); }NewNumber = "yes";opvalue = '-';Display(Number1);}function MultButton(x) {if(x == 1) EqualButton();if(Number2 != "") {Number1 = parseFloat(Number1) * parseFloat(Number2); }NewNumber = "yes";opvalue = '*';Display(Number1);}function DivButton(x) {if(x == 1) EqualButton();if(Number2 != "") {Number1 = parseFloat(Number1) / parseFloat(Number2); }NewNumber = "yes";opvalue = '/';Display(Number1);}function SqrtButton() {Number1 = Math.sqrt(Number1); NewNumber = "blank";Display(Number1);}function PercentButton() {if(NewNumber != "blank") { Number2 *= .01;NewNumber = "blank";Display(Number2);}}function RecipButton() {Number1 = 1/Number1; NewNumber = "blank";Display(Number1);}function NegateButton() {Number1 = parseFloat(-Number1); NewNumber = "no";Display(Number1);}function EqualButton() {if(opvalue == '+') AddButton(0);if(opvalue == '-') SubButton(0);if(opvalue == '*') MultButton(0);if(opvalue == '/') DivButton(0); Number2 = "";opvalue = "";}</script></HEAD><BODY><center><form name="calculator"><table bgcolor="#aaaaaa" width=230> <tr><td><table bgcolor="#cccccc" border=1><tr><td><table border=0 cellpadding=0><tr><td bgcolor="#000080"></td></tr><tr><td><table width="100%" border=0><tr><td colspan=6><input type="text" readOnly name="answer" size=30 maxlength=30 onChange="CheckNumber(this.value)"></td></tr><tr><td colspan=6><table border=0 cellpadding=0><tr><td><input type="text" name="mem" size=3 maxlength=3 readOnly style="background:menu"> <input type="button" name="backspace" class="redl" value="退格" onClick="Backspace(document.calculator.answer.value); return false;"> <input type="button" name="CE" class="redl" value="CE" onClick="CECalc(); return false;"> <input type="reset" name="C" class="redl" value="C" onClick="ClearCalc(); return false;"></td></tr></table></td></tr><tr><td><input type="button" name="MC" class="red" value=" MC " onClick="MemoryClear(); return false;"></td><td><input type="button" name="calc7" class="blue" value=" 7 " onClick="CheckNumber('7'); return false;"></td><td><input type="button" name="calc8" class="blue" value=" 8 " onClick="CheckNumber('8'); return false;"></td><td><input type="button" name="calc9" class="blue" value=" 9 " onClick="CheckNumber('9'); return false;"></td><td><input type="button" name="divide" class="red" value=" / " onClick="DivButton(1); return false;"></td><td><input type="button" name="sqrt" class="blue" value="sqrt" onClick="SqrtButton(); return false;"></td></tr><tr><td><input type="button" name="MR" class="red" value=" MR " onClick="MemoryRecall(Memory); return false;"></td><td><input type="button" name="calc4" class="blue" value=" 4 " onClick="CheckNumber('4'); return false;"></td><td><input type="button" name="calc5" class="blue" value=" 5 " onClick="CheckNumber('5'); return false;"></td><td><input type="button" name="calc6" class="blue" value=" 6 " onClick="CheckNumber('6'); return false;"></td><td><input type="button" name="multiply" class="red" value=" * " onClick="MultButton(1); return false;"></td><td><input type="button" name="percent" class="blue" value=" % " onClick="PercentButton(); return false;"></td></tr><tr><td><input type="button" name="MS" class="red" value=" MS "onClick="MemorySubtract(document.calculator.answer.value); return false;"></td><td><input type="button" name="calc1" class="blue" value=" 1 " onClick="CheckNumber('1'); return false;"></td><td><input type="button" name="calc2" class="blue" value=" 2 " onClick="CheckNumber('2'); return false;"></td><td><input type="button" name="calc3" class="blue" value=" 3 " onClick="CheckNumber('3'); return false;"></td><td><input type="button" name="minus" class="red" value=" - " onClick="SubButton(1); return false;"></td><td><input type="button" name="recip" class="blue" value="1/x " onClick="RecipButton(); return false;"></td></tr><tr><td><input type="button" name="Mplus" class="red" value=" M+ " onClick="MemoryAdd(document.calculator.answer.value); return false;"></td><td><input type="button" name="calc0" class="blue" value=" 0 " onClick="CheckNumber('0'); return false;"></td><td><input type="button" name="negate" class="blue" value="+/- " onClick="NegateButton(); return false;"></td><td><input type="button" name="dot" class="blue" value=" . " onClick="CheckNumber('.'); return false;"></td><td><input type="button" name="plus" class="red" value=" + " onClick="AddButton(1); return false;"></td><td><input type="button" name="equal" class="red" value=" = " onClick="EqualButton(); return false;"></td></tr></table></td></tr></table></td></tr></table></td></tr></table></form></center><script language=javascript>function keyDown(){var iCode=window.event.keyCode;//alert(iCode);if(event.shiftKey){switch(iCode){case 56:document.all.multiply.click();break;case 59:document.all.minus.click();break;case 60:document.all.plus.click();break;}}if(!event.shiftKey&&!event.ctrlKey&&!event.altKey) {switch (iCode){case 8:document.all.backspace.click();break;case 187:document.all.equal.click();break;case 96:document.all.calc0.click();break;case 97:document.all.calc1.click();break;case 98:document.all.calc2.click();break;case 99:document.all.calc3.click();break;case 100:document.all.calc4.click();break;case 101:document.all.calc5.click();break;case 102:document.all.calc6.click();break;case 103:document.all.calc7.click();break;case 104:document.all.calc8.click();break;case 105:document.all.calc9.click();break;case 110:document.all.dot.click();break;case 13:document.all.equal.click();break;case 107:document.all.plus.click();break;case 109:document.all.minus.click();break;case 106:document.all.multiply.click();break;case 111:document.all.divide.click();break;case 48:document.all.calc0.click();break;case 49:document.all.calc1.click();break;case 50:document.all.calc2.click();break;case 51:document.all.calc3.click();break;case 52:document.all.calc4.click();break;case 53:document.all.calc5.click();break;case 54:document.all.calc6.click();break;case 55:document.all.calc7.click();break;case 56:document.all.calc8.click();break;case 57:document.all.calc9.click();break;case 190:document.all.dot.click();break;case 13:document.all.equal.click();break;case 191:document.all.divide.click();break;}}//event.keyCode=0;//event.returnV alue=false;}window.document.attachEvent("onkeydown",keyDown) </script></BODY></HTML>。
JS实现计算器详解及实例代码(一)
JS实现计算器详解及实例代码(⼀)Javascript 实现计算器:系列⽂章:⼩型JavaScript计算器⾃⼰寻思出的解决⽅案,⽐较笨拙的⽅法,虽然完成了但是还有不少bug,⽤的⽅法也不是最有效的,基本功能算是完成了,⼀些⼩的细节地⽅也考虑到了,但是还有其他的细节需要处理。
总体设计思路是,先画草图 -> 设计UI -> 编写UI代码 -> 编写CSS -> 编写JS逻辑代码;⾯板(main-board)⾯板整体尺⼨设计标题栏(board-title)字体: font: 30px/50px “Comic Sans MS”, “微软雅⿊”;宽⾼:(100%, 50px);屏显区(board-result)数字显⽰区(result-up):表达式显⽰区(result-down):按钮区(board-keys),使⽤表格完成,然后给每个td添加onclick事件完成界⾯导⼊新字体// main.css@font-face {font-family: Lovelo-Black;/×定义font的名字×/src: url('font/Lovelo Black.otf');/*把下载的字体⽂件引⼊进来×/}代码分析代码组织结构计算器对象:Calculator;计算器属性:bdResult: 计算器⾯板上的屏显区DOM对象;operator:操作符数组,包括'+,-,×,÷,=';digits:有效数字字符,包括'0-9'和点'.';dot, equal, zero:'.', ‘=', ‘0'对应三个字符,点,等号,字符'0';digit:屏显区上层的显⽰的当前输⼊的数字;expression:屏显区下层的显⽰的输⼊的数字和操作符组成的表达式;resSpan:屏显区上层的显⽰当前数字的span对象;resDown:屏显区下层的显⽰表达式的div对象;last:上⼀次输⼊的按钮内容;allDigits:⽤表达式解析出来的表达式中所有的有效数字;ops:⽤表达式字符串解析出来的表达式中所有的操作符;hasEqual:判断是否按了'='等号的标识符;lastRes:上⼀次计算出来的结果[TODO],尚未⽤到,待实现可以连续计算;计算器⽅法:1. init:计算器初始化⽅法;2. addTdClick:给每个td即计算器按钮添加点击事件;3. calculatorClickEvent:点击事件;4. btnClickHanlder:点击事件处理函数;5. showCurrRes:处理屏显区上层和下层将要显⽰的内容;6. showText:将通过showCurrRes处理的结果显⽰出来;7. addZero:对表达式前⾯加'0'操作;8. calResult:计算结果;9. clearData:清空数据;10. hasOperator:判断表达式中是否有操作符;11. isOperator:判断当前字符是否是操作符;12. delHeadZero:删除表达式开头的'0';辅助⽅法getResSpan:获取屏显上层的span对象;$tag:根据标签名去获取标签对象;$:根据id去获取DOM对象;代码逻辑使⽤⽅法引⼊Calculator.js⽂件(在编写完UI的基础上)创建对象并初始化:new Calculator().init();计算器对象// 计算器对象function Calculator() {// 私有属性this.bdResult = $("board-result"); // 计算机⾯板结果显⽰区对象this.operator = ['+', '-', '×', '÷', '='];this.digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']; // 组成有效数字的数字数组this.dot = '.';this.equal = '=';this.zero = '0';this.digit = ""; // 当前输⼊的数字this.expression = ""; // 表达式this.resSpan = getResSpan(); // 数字显⽰区this.resDown = $("result-down"); // 表达式显⽰区st = ""; // 上⼀次按下的按钮内容this.allDigits = []; // 从表达式中获取的所有数字组成的数组,将⽤来和ops中的操作符对应计算出结果 this.ops = []; // 所有操作符组成的数组this.hasEqual = false; // 判断是否按下了'='键stRes = 0; // 上⼀次计算的结果,即上⼀次按等号后计算出的值// 私有⽅法}添加点击事件(注意this在闭包⾥的引⽤问题)// 为td添加点击事件Calculator.prototype.addTdClick = function () {var tds = $tag("td");var that = this; // 需要注意保存this的引⽤// 为每个td添加点击事件for (var i = 0; i < tds.length; i++) {tds[i].onclick = function (){// alert(this.innerText);var text = this.innerText;that.calculatorClickEvent(text);};}};计算器点击事件处理⼊⼝// 计算器按钮事件Calculator.prototype.calculatorClickEvent = function (btnText) {// 上⼀个按键是'='if (this.hasEqual) {this.hasEqual = false;this.clearData();}// 结果显⽰在board-result⾥if (btnText != "AC" && btnText != "CE") {this.btnClickHanlder(btnText);} else { // AC或CE清零this.clearData();}};计算器点击事件处理程序// 计算器的按键事件处理Calculator.prototype.btnClickHanlder = function (btnText) {if ((btnText >= '0' && btnText <= '9') || btnText == this.dot) { // 数字键处理// 如果上⼀个是操作符,则清空当前数字区if (this.isOperator(st)) {this.resSpan.innerText = '';this.digit = '';} else if ((btnText == this.dot) && (st == this.dot)) {// 如果上⼀个也是点,则对本次的点按钮不做响应return;}this.digit += btnText;this.expression += btnText;} else if (this.isOperator(btnText)) { // 操作符处理// 如果当前表达式为'0',按'=',不给响应if ((btnText == this.equal) && (this.resDown.innerText == this.zero || this.resDown.innerText == "")) return; // 如果上⼀个是⾮'='的操作符则不进⾏处理if (!this.isOperator(st) && btnText == this.equal) { // '='处理this.showCurrRes(this.zero, this.expression + btnText); // 计算结果显⽰在表达式区域return;} else if (this.isOperator(st)) {// 上⼀个是操作符,此次的操作符不做记录return;} else {this.expression += btnText;}}this.showCurrRes(this.digit, this.expression);st = btnText;};处理将要显⽰的表达式和当前输⼊的数字// 显⽰当前结果的触发⽅法Calculator.prototype.showCurrRes = function (digit, expression) {if (!expression) return;this.showText(digit, expression);// 1. 没有'=',表⽰还没有到计算结果的时候,直接退出if (expression.indexOf(this.equal) == -1) return;// 计算出了结果this.hasEqual = true;// 2. 处理只按了数字然后直接按了等号的情况,即:'234='则直接返回234var tmpStr = this.delHeadZero(expression.substr(0, expression.length - 1)); // 去掉最后⼀个'='if (!this.hasOperator(tmpStr)) {this.showText(tmpStr, expression + tmpStr);return;}// 3. 处理表达式字符串,且计算出结果var start = 0;for (var i = 0; i < expression.length; i++) {var c = expression[i];if (this.isOperator(c)) { // 操作符this.ops.push(c); // 保存操作符var numStr = expression.substr(start, i + 1); // 数字字符串var number = 0;// 浮点数和整型处理if (numStr.indexOf(this.dot)) {number = parseFloat(numStr);} else {number = parseInt(numStr);}this.allDigits.push(number); // 保存数字start = i + 1; // 重设数字起始位置,即操作符的下⼀个字符开始}}// ⽤allDigits和ops去计算结果var res = this.calResult();// 保存此次计算结果,作为下⼀次计算⽤ [TODO]stRes = res;// 将结果显⽰出来this.showText(res + '', expression + res);};将处理结果显⽰到屏显区// 将表达式和计算结果显⽰到屏显区Calculator.prototype.showText = function (digitStr, expression) {// 先删除开头的'0'var expStr = this.delHeadZero(expression);var digStr = this.delHeadZero(digitStr);// 然后再根据情况决定是否添加'0'var tmp = expression == this.zero ? expression : this.addZero(expStr);;var dig = digitStr == this.zero ? digitStr : this.addZero(digStr);this.resSpan.innerText = dig;// 如果表达式第⼀个是操作符,则表⽰之前按的是'0',则给补上'0',因为前⾯将开头的'0'都删掉了if (this.isOperator(tmp[0])) {tmp = this.zero + tmp;}this.resDown.innerText = tmp;}计算结果函数// 计算结果Calculator.prototype.calResult = function () {var first = 0;var second = 0;var res = 0;for (var i = 0; i < this.ops.length; i++) {first = this.allDigits[i];second = this.allDigits[i + 1];switch (this.ops[i]) {case '+':res = first + second;break;case '-':res = first - second;break;case '×':res = first * second;break;case '÷':res = first / second;break;default:break;}this.allDigits[i + 1] = res;}return res;};清空数据// 计算完⼀次,清空所有数据,以备下次计算使⽤Calculator.prototype.clearData = function () {this.allDigits = [];this.ops = [];this.expression = this.zero;this.digit = '';this.resSpan.innerText = this.zero;this.resDown.innerText = this.zero;};辅助函数处理表达式开头的'0'问题(第⼀个按钮是0键或者第⼀个是⼩于1的浮点数,表达式需要补零;) // 开头添加'0',防⽌重复出现或者没有'0'情况Calculator.prototype.addZero = function (expression) {if (!expression) return this.zero;if (expression[0] == this.dot) { // 浮点数return this.zero + expression;} else {return expression;}};开头去零函数// 去开头的零Calculator.prototype.delHeadZero = function (str) {// 先把开头的‘0'都删掉var tmp = "";tmp = str.replace(/^[0]+/gi, "");if (tmp[0] == this.dot) { // 浮点数重新补上'0'tmp = this.zero + tmp;}return tmp;};判断字符串⾥是否含有操作符// 判断表达式中是否含有操作符Calculator.prototype.hasOperator = function (str) {if (!str) return;for (var i = 0; i < this.operator.length; i++) {if (str.indexOf(this.operator[i]) >= 0) {return true;}}return false;};其他函数// 获取输⼊的数字显⽰区对象function getResSpan() {return $("result-up").getElementsByTagName("span")[0];}// 根据标签名获取DOM对象function $tag(tagName) {return document.getElementsByTagName(tagName);}// 根据ID获取DOM对象function $(id) {return document.getElementById(id);}问题⽂字底部显⽰:通过设置⾏⾼处理;通过⼀次性解析表达式需要考虑表达式开头是否需要'0'存在;感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!。
js简单计算器代码
js简单计算器代码JavaScript是一种广泛应用于网页开发的编程语言,它具有强大的计算能力。
在本文中,我们将探讨如何使用JavaScript编写一个简单的计算器。
我们需要一个HTML页面来容纳我们的计算器。
在HTML文件中,我们可以使用<input>元素来创建用于输入数字和操作符的文本框,使用<button>元素来创建用于触发计算的按钮。
接下来,我们需要编写一些JavaScript代码来处理用户的输入并进行计算。
在编写JavaScript代码之前,我们需要先为每个按钮和文本框添加一个唯一的id属性,以便在代码中引用它们。
例如,我们可以为数字按钮添加id="digit1",id="digit2",依此类推;为操作符按钮添加id="add",id="subtract",以此类推;为文本框添加id="result"。
接下来,我们可以使用JavaScript的事件监听器来监听按钮的点击事件。
当用户点击数字按钮时,我们可以将对应的数字添加到文本框中;当用户点击操作符按钮时,我们可以将对应的操作符添加到文本框中。
此外,我们还可以添加一个“清除”按钮,当用户点击该按钮时,可以清空文本框中的内容。
在编写事件监听器的代码时,我们需要使用JavaScript的DOM (文档对象模型)操作来获取按钮和文本框的引用。
例如,我们可以使用document.getElementById()方法来获取按钮和文本框的引用,然后使用addEventListener()方法来为按钮添加点击事件的监听器。
当用户点击“计算”按钮时,我们需要编写代码来解析文本框中的内容,并进行相应的计算。
在JavaScript中,我们可以使用eval()函数来执行字符串形式的表达式。
例如,如果文本框中的内容为"2 + 3",我们可以使用eval("2 + 3")来计算结果并将结果显示在文本框中。
网页计算器--JS代码
网页计算器的界面:该计算其代码如下:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head id="Head1" runat="server"><title>网页计算器</title></head><script type="text/javascript">var t;t = self.setInterval("ShowTime()", 10);var Exp = "";function ShowTime() {var Today = new Date(); //这条语句要放在该函数内,而不能作为全局变量hours = Today.getHours(); minutes = Today.getMinutes(); second = Today.getSeconds();if (hours < 10) hours = "0" + hoursif (minutes < 10) minutes = "0" + minutesif (second < 10) second = "0" + seconddocument.all.time.value = hours + ":" + minutes + ":" + second;}function MyFun() {alert(Exp);}//获取光标在ID为obj控件的位置,返回下标function getPos(obj) {obj.focus();var s = document.selection.createRange();s.setEndPoint("StartToStart", obj.createTextRange())return s.text.length;}//设置光标位置的函数function setCursor(ctrl, pos){if(ctrl.setSelectionRange){ctrl.focus();ctrl.setSelectionRange(pos,pos);}else if (ctrl.createTextRange){var range = ctrl.createTextRange();range.collapse(true);range.moveEnd('character', pos);range.moveStart('character', pos);range.select();}}//删除表达式中的元素function Delete() {var Len = document.all.In.value.length;Exp = document.all.In.value;var Arr = Exp.split("");var pos = getPos(In);Arr.splice(pos - 1, 1, "");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Exp = toStr;Arr = toStr.split("");document.all.In.value = toStr;setCursor(In,pos - 1);}//清除表达式function Clearn() {document.all.In.value = "";}function addParentheses(strObj) {var Temp = strObj;var Arr = Temp.split("");for (var i = 0; i < Arr.length; ++i) {if (Arr[i] == "s" || Arr[i] == "c" || Arr[i] == "t" || Arr[i] == "√"){if (Arr[i + 1] != "("){Arr.splice(i, 1, Arr[i] + "(");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");var Index = i + 2;if (Arr[Index] != "s" && Arr[Index] != "c" && Arr[Index] != "t" && Arr[Index] != "√"){var Bol = true;while (Bol) {if (Arr[Index + 1] == "+" || Arr[Index + 1] == "-" || Arr[Index + 1] == "*" || Arr[Index + 1] == "/" || Arr.length <= (Index + 1)){Arr.splice(Index, 1, Arr[Index] + ")");var toStr = "";for(var l = 0; l < Arr.length; ++l)toStr += Arr[l];Arr = toStr.split("");Bol = false;}++Index;}var S = "";for(var k = 0; k < Arr.length; ++k)S += Arr[k];S = Arr.toString();}//如果参数是函数else{var val = 0;var Bol = true;var hasPar = false;while (Bol){if (Arr[Index + 1] == "("){hasPar = true;val++;}if (Arr[Index + 1] == ")")--val;//没有括号的情况if (((Arr[Index + 1] == "+" || Arr[Index + 1] == "-" || Arr[Index + 1] == "*" || Arr[Index + 1] == "/") && !hasPar) || (Index + 1) >= Arr.length){Arr.splice(Index, 1, Arr[Index] + ")");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");Bol = false;}//有括号的情况if (val == 0 && hasPar){Arr.splice(Index + 1, 1,Arr[Index + 1] + ")");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");Bol = false;}++Index;}}}}var Str = "";for (var m = 0; m < Arr.length; ++m)Str += Arr[m];Exp = Str;}}//在表达式中添加表达式元素function addElement(Ele) {var Arr = new Array();Exp = document.all.In.value;var Index = getPos(In);if (Index >= Exp.length) {Exp += Ele;}else {Arr = Exp.split("");var Cha = Arr[Index];Arr.splice(Index, 1, Ele + Cha);var Str = "";for (var i = 0; i < Arr.length; ++i)Str += Arr[i];Exp = Str;}document.all.In.value = Exp;setCursor(In,Index + Ele.length);}function Input1() {addElement("1");}function Input2() {addElement("2");}function Input3() {addElement("3");}function Input4() {addElement("4");}function Input5() {addElement("5");}function Input6() {addElement("6");}function Input7() {addElement("7");}function Input8() {addElement("8");}function Input9() {addElement("9");}function Input0() {addElement("0");}function InputDot() {addElement(".");}function InputSin() {addElement("sin");}function InputCos() {addElement("cos");}function InputTan() {addElement("tan");}function InputSqtr() {addElement("√");}function InputAdd() {addElement("+");}function InputMin() {addElement("-");}function InputMult() {addElement("*");}function InputDiv() {addElement("/");}function InputPI() {addElement("3.141592"); }function InputLPar() {addElement("(");}function InputRPar() {addElement(")");}function InputLn() {addElement("ln");}function InputLog() {addElement("log");}function InputEql() {Exp = document.all.In.value;var Str = "";Str = Exp.replace(/sin/g, "s");Str = Str.replace(/cos/g, "c");Str = Str.replace(/tan/g, "t");addParentheses(Str);Exp = Exp.replace(/t/g, "Math.tan");Exp = Exp.replace(/s/g, "Math.sin");Exp = Exp.replace(/c/g, "Math.cos");Exp = Exp.replace(/√/g, "Math.sqrt");var result = eval(Exp);document.all.Restlt.value = result;}</script><body ><table border="8" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><label id = "Lab" ></label> 计算器</td></tr></table><table border="1" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input id = "In" type = "text" style="width:160px" /></td><td><input id = "bs" type = "button" value = "Backspace" style="width:75px" onclick = "Delete();"/></td></tr></table><table border="1" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input id = "Restlt" type = "text" style="width:110px" /></td><td><input id = "Clearn" type = "button" value = "Clearn" style="width:60px" onclick = "Clearn();" /></td><td><input id = "time" type = "text" style="width:60px" /></td></tr></table><table border="5" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input type = "button" id = "N1" style="width:50px" value = "1" onclick = "Input1();"/></td><td><input type = "button" id = "N2" style="width:50px" value = "2" onclick = "Input2();" /></td><td><input type = "button" id = "N3" style="width:50px" value = "3" onclick = "Input3();" /></td><td><input type = "button" id = "Add" style="width:40px" value = "+" onclick ="InputAdd();" /></td><td><input type = "button" id = "Sub" style="width:40px" value = "-" onclick = "InputMin();"/></td></tr><tr><td><input type = "button" id = "N4" style="width:50px" value = "4" onclick = "Input4();"/></td><td><input type = "button" id = "N5" style="width:50px" value = "5" onclick = "Input5();" /></td><td><input type = "button" id = "N6" style="width:50px" value = "6" onclick = "Input6();" /></td><td><input type = "button" id = "Times" style="width:40px" value = "*" onclick = "InputMult();" /></td><td><input type = "button" id = "Divd" style="width:40px" value = "/" onclick = "InputDiv();" /></td></tr><tr><td><input type = "button" id = "N7" style="width:50px" value = "7" onclick = "Input7();"/></td><td><input type = "button" id = "N8" style="width:50px" value = "8" onclick = "Input8();" /></td><td><input type = "button" id = "N9" style="width:50px" value = "9" onclick = "Input9();" /></td><td><input type = "button" id = "Sqt" style="width:40px" value = "√" onclick = "InputSqtr();" /></td><td><input type = "button" id = "sin" style="width:40px" value = "sin" onclick = "InputSin();" /></td></tr><tr><td><input type = "button" id = "N0" style="width:50px" value = "0" onclick = "Input0();"/></td><td><input type = "button" id = "Dot" style="width:50px" value = "." onclick = "InputDot();" /></td><td><input type = "button" id = "Eql" style="width:50px" value = "=" onclick = "InputEql();" /></td><td><input type = "button" id = "cos" style="width:40px" value = "cos" onclick = "InputCos();" /></td><td><input type = "button" id = "tan" style="width:40px" value = "tan" onclick = "InputTan();" /></td></tr><tr><td><input type = "button" id = "PI" style="width:50px" value = "π" onclick = "InputPI();"/></td><td><input type = "button" id = "L_Par" style="width:50px" value = "(" onclick = "InputLPar();" /></td><td><input type = "button" id = "R_Par" style="width:50px" value = ")" onclick = "InputRPar();" /></td><td><input type = "button" id = "Ln" style="width:40px" value = "ln" onclick = "InputLn();" /></td><td><input type = "button" id = "Log" style="width:40px" value = "log" onclick = "InputLog();" /></td></tr></table><input id = "Input" type = "button" value = "click" onclick = "MyFun();" /> <form id="form1" runat="server"><div></div></form></body></html>。
简易的JS计算器实现代码
简易的JS计算器实现代码看看⼿机中的计算器,分为普通计算器和科学计算器⾃认脑袋不够⼤,就实现⼀个普通版本的吧(⽀持正负数加减乘除等基本连续的运算,未提供括号功能)看看图⽰效果:⼀、知识准备1+1 = ?正常来说,我们看到这个表达式都知道怎么运算,知道运算结果但计算机不⼀样,计算机⽆法识别出这串表达式,它只能识别特定的规则:前缀表达式+ 1 1 或后缀表达式1 1 +举个栗⼦(3 + 4) × 5 - 6 就是中缀表达式- × + 3 4 5 6 前缀表达式3 4 + 5 × 6 - 后缀表达式所以为了实现程序的⾃动运算,我们需要将输⼊的数据转化为前缀或后缀表达式前缀、中缀、后缀表达式的概念以及相互转换⽅法在这⾥就不多说了,这篇博⽂说得⽐较清楚了所以,在这个计算器的实现中,采⽤了后缀表达式的实现⽅式,参考以上⽂章,重点关注这两个算法:与转换为前缀表达式相似,遵循以下步骤:(1) 初始化两个栈:运算符栈S1和储存中间结果的栈S2;(2) 从左⾄右扫描中缀表达式;(3) 遇到操作数时,将其压⼊S2;(4) 遇到运算符时,⽐较其与S1栈顶运算符的优先级:(4-1) 如果S1为空,或栈顶运算符为左括号“(”,则直接将此运算符⼊栈;(4-2) 否则,若优先级⽐栈顶运算符的⾼,也将运算符压⼊S1(注意转换为前缀表达式时是优先级较⾼或相同,⽽这⾥则不包括相同的情况);(4-3) 否则,将S1栈顶的运算符弹出并压⼊到S2中,再次转到(4-1)与S1中新的栈顶运算符相⽐较;(5) 遇到括号时:(5-1) 如果是左括号“(”,则直接压⼊S1;(5-2) 如果是右括号“)”,则依次弹出S1栈顶的运算符,并压⼊S2,直到遇到左括号为⽌,此时将这⼀对括号丢弃;(6) 重复步骤(2)⾄(5),直到表达式的最右边;(7) 将S1中剩余的运算符依次弹出并压⼊S2;(8) 依次弹出S2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式(转换为前缀表达式时不⽤逆序)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
数学与计算机学院实验报告用javascript制作计算器5的阶乘的结果:源代码:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><title> 计算器</title><script type="text/jabascript">var x;var y;var num;var flag;function chushihua(){x="start";y="start";num=0;flag=false;}function qingkong(){jisuan.input.value="0";x="start";y="start";}function addNum(i){if(flag==true)//是运算符{jisuan.input.value=i;flag=false;}else{if(jisuan.input.value=="0"){jisuan.input.value=i;}elsejisuan.input.value+=i;//不是第一个数}}function caozuo(x){flag=true;if(y=="start"){num=jisuan.input.value;y=x;}else{count();y=x;}}function count(){if(y!="start"){switch(y){case "+":num=parseFloat(num)+parseFloat(jisuan.input.value);break;case "-": num=parseFloat(num)-parseFloat(jisuan.input.value);break;case "*":num=parseFloat(num)*parseFloat(jisuan.input.value);break;case "/":num=parseFloat(num)/parseFloat(jisuan.input.value);break;}jisuan.input.value=num;flag=true;}flag="false";}function hanshu(fun){switch(fun){case "sin":jisuan.input.value=Math.sin(jisuan.input.value);break;case "cos":jisuan.input.value=Math.cos(jisuan.input.value);break;case "tan":jisuan.input.value=Math.tan(jisuan.input.value);break;case "asin":jisuan.input.value=Math.asin(jisuan.input.value);break;case "acos":jisuan.input.value=Math.acos(jisuan.input.value);break;case "atan":jisuan.input.value=Math.atan(jisuan.input.value);break;case "log":jisuan.input.value=Math.log(jisuan.input.value);break;case "ln":jisuan.input.value=Math.ln(jisuan.input.value);break;case "sqrt":jisuan.input.value=Math.sqrt(jisuan.input.value);break;case "1/x":jisuan.input.value=1/jisuan.input.value;break;case "%":jisuan.input.value=jisuan.input.value*0.01;break;}}function jiecheng(i){var num =jisuan.input.value;var sum = 1;for(var i = 1; i <= num; i++){sum *= i;}jisuan.input.value=sum;}function tuige(){jisuan.input.value = jisuan.input.value.substring(0,jisuan.input.value.length-1)jisuan.input.title = jisuan.input.value.substring(jisuan.input.title.length-1) }</script><style type="text/css">#按钮{width:55px;height:35px;color:blue;font-size:18px;}</style></head><body onload="chushihua()"><script src="6.js" language="javascript"></script><form name="jisuan"><table border="1" cellspacing=6 ><tr><td colspan="5" align=center><input type="text" size="43" value="0" name="input" style="height:25px;color:blue;font-weight:bold"</td></tr><tr><td><input type="button" value="7" onclick="addNum(7)" id=按钮></td><td><input type="button" value="8" onclick="addNum(8)" id=按钮></td><td><input type="button" value="9" onclick="addNum(9)" id=按钮></td><td><input type="button" value="退格" onclick="tuige()" id=按钮></td><td><input type="button" value="清空" onclick="qingkong()" id=按钮></td></tr><tr><td><input type="button" value="4" onclick="addNum(4)" id=按钮></td><td><input type="button" value="5" onclick="addNum(5)" id=按钮></td><td><input type="button" value="6" onclick="addNum(6)" id=按钮></td><td><input type="button" value="PI" onclick="jisuan.input.value=Math.PI" id=按钮></td><td><input type="button" value="E" onclick="jisuan.input.value=Math.E" id=按钮></td></tr><tr><td><input type="button" value="1" onclick="addNum(1)" id=按钮></td><td><input type="button" value="2" onclick="addNum(2)" id=按钮></td><td><input type="button" value="3" onclick="addNum(3)" id=按钮></td><td><input type="button" value="+" onclick="caozuo('+')" id=按钮></td><td><input type="button" value="-" onclick="caozuo('-')" id=按钮></td></tr><tr><td><input type="button" value="0" onclick="addNum('0')" id=按钮></td><td><input type="button" value="·" onclick="addNum('.')" id=按钮></td><td><input type="button" value="n!" onclick="jiecheng()" id=按钮></td><td><input type="button" value="*" onclick="caozuo('*')" id=按钮></td><td><input type="button" value="/" onclick="caozuo('/')" id=按钮></td></tr><tr><td><input type="button" value="sin" onclick="hanshu('sin')" id=按钮></td><td><input type="button" value="cos" onclick="hanshu('cos')" id=按钮></td><td><input type="button" value="tan" onclick="hanshu('tan')" id=按钮></td><td><input type="button" value="(" onclick="caozuo('(')" id=按钮></td><td><input type="button" value=")" onclick="caozuo(')')" id=按钮></td></tr><tr><td><input type="button" value="asin" onclick="hanshu('asin')" id=按钮></td><td><input type="button" value="acos" onclick="hanshu('acos')" id=按钮></td><td><input type="button" value="atan" onclick="hanshu('atan')" id=按钮></td><td><input type="button" value="1/x" onclick="hanshu('1/x')"id=按钮></td><td><input type="button" value="%" onclick="hanshu('%')" id=按钮></td></tr><tr><td><input type="button" value="log" onclick="hanshu('log')" id=按钮></td><td><input type="button" value="ln" onclick="hanshu('ln')" id=按钮></td><td><input type="button" value="sqrt" onclick="hanshu('sqrt')" id=按钮></td><td colspan="2"><input type="button" value="=" onclick="caozuo('=')"style="width:120px;height:35px;"></td></tr></table></form></body></html>五、总结在我刚开始用JavaScript写程序的时候,感觉很不习惯,因为它以前学习的C语言有些相似,但具体又不一样,语法要求不是那么严格。