javascript简易计算器?js做简易计算器
老铁们,大家好,相信还有很多朋友对于javascript简易计算器和js做简易计算器的相关问题不太懂,没关系,今天就由我来为大家分享分享javascript简易计算器以及js做简易计算器的问题,文章篇幅可能偏长,希望可以帮助到大家,下面一起来看看吧!
用javascript编写计算器
用javascript编写计算器:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""">
<htmlxmlns="">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>Javascript实现计算器</title>
<styletype="text/css">
input{
width:30px;
height:20px;
text-align:center;
}
#tbCalculatortd
{
text-align:center;
vertical-align:middle;
}
</style>
<scripttype="text/javascript">
varresult;//保存点击运算符之前输入框中的数值
varoperator;//保存运算符
varisPressEqualsKey=false;//记录是否按下”=“键
//数字键事件
functionconnectionDigital(control)
{
vartxt=document.getElementById('txtScream');
if(isPressEqualsKey)
{
txt.value="";//已进行过计算,则清空数值输入框重新开始
isPressEqualsKey=false;
}
//数值输入已经存在小数点,则不允许再输入小数点
if(txt.value.indexOf('.')>-1&&control.value=='.')
returnfalse;
txt.value+=control.value;//将控件值赋给数值输入框中
}
//退格键事件
functionbackspace()
{
vartxt=document.getElementById('txtScream');
txt.value=txt.value.substring(0,txt.value.length-1);
}
//ce键事件:清空数字输入框
functionclearAll()
{
document.getElementById('txtScream').value="";
result="";
operator="";
}
//+、-、*、/事件
functioncalculation(control)
{
//将运算符保存入全局变量中
operator=control.value;
vartxt=document.getElementById('txtScream');
if(txt.value=="")returnfalse;//数值输入框中没有数字,则不能输入运算符
//将数值输入框中的值保存到计算表达式中
result=txt.value;
//清空输入框,以待输入操作值
txt.value="";
}
//计算结果
functiongetResult()
{
varopValue;
//计算表达式中存在运算符
varsourseValue=parseFloat(result);
vartxt=document.getElementById('txtScream');
if(operator=='*')
opValue=sourseValue*parseFloat(txt.value);
elseif(operator=='/')
opValue=sourseValue/parseFloat(txt.value);
elseif(operator=='+')
opValue=sourseValue+parseFloat(txt.value);
elseif(operator=='-')
opValue=sourseValue-parseFloat(txt.value);
txt.value=opValue;
isPressEqualsKey=true;
result="";
opValue="";
}
</script>
</head>
<body>
<tableid="tbCalculator"width="200"border="1"align="center"cellpadding="0"cellspacing="0"bordercolor="#0066FF">
<tr>
<tdheight="30"colspan="4"align="center">
<inputtype="text"name="txtScream"id="txtScream"style="width:180px;border-style:none;text-align:right;"readonly="readonly"/></td>
</tr>
<tr>
<tdheight="30"colspan="2">
<inputtype="button"name="btnCE"id="btnCE"value="C E"style="width:80px;"align="right";onclick="clearAll();"/></td>
<tdheight="30"colspan="2">
<inputtype="button"name="btn10"id="btn10"value="Backspace"style="width:80px;"align="right";onclick="backspace();"/></td>
</tr>
<tr>
<tdheight="30"><inputtype="button"name="btn7"id="btn7"value="7"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn8"id="btn8"value="8"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn9"id="btn9"value="9"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn6"id="btn6"value="/"onclick="calculation(this);"/></td>
</tr>
<tr>
<tdheight="30">
<inputtype="button"name="btn4"id="btn4"value="4"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn5"id="btn5"value="5"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn6"id="btn6"value="6"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn13"id="btn13"value="*"onclick="calculation(this);"/></td>
</tr>
<tr>
<tdheight="30">
<inputtype="button"name="btn1"id="btn1"value="1"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn2"id="btn2"value="2"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn3"id="btn3"value="3"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btn18"id="btn18"value="-"onclick="calculation(this);"/></td>
</tr>
<tr>
<tdheight="30"><inputtype="button"name="btn0"id="btn0"value="0"onclick="connectionDigital(this);"/></td>
<td><inputtype="button"name="btndot"id="btndot"value="."onclick="connectionDigital(this);"/></td>
<td><inputname="btn22"type="button"id="btn22"value="="onclick="getResult();"/></td>
<td><inputtype="button"name="btn23"id="btn23"value="+"onclick="calculation(this);"/></td>
</tr>
</table>
</body>
</html>
JAVASCRIPT做计算器
this在JS里是指自身,就是指它自己这个元素,这儿就是指input
而this.form就是指这个input的父级元素form了
函数compute(this.form)把网页中的这个form给做为一个obj对象参数传递给了compute来执行下面
obj.expr.value=eval(obj.expr.value)
这儿的obj其实就是那个form标签,而expr是一个id
这儿是一个赋值语句,就是把obj.expr.value的值重新计算并回赋给它自己
虽然那个form中有多个input,但这些都是在form里面的,就是它的子元素,所以把compute(this.form)放在谁那儿都是可以的。
还有3个input的click事件,激活了enter(obj, string)的函数,这儿的obj还是一个对象,string是字符串
这个函数执行obj.expr.value+= string
在JS中+=就相当于把自身再加等号右边的字符,如:a+=1与a=a+1相同
这样就把计算后的数据又赋值给了obj.expr.value
由此达到计算器的目的
JavaScript 计算器大数精度失真:原因、调试与应对策略
JavaScript计算器大数精度失真的根本原因是其Number类型采用IEEE 754双精度浮点数标准,该标准对整数精度的安全范围有限制,超出后会导致四舍五入和近似表示,从而引发精度丢失。以下是具体分析、调试方法及应对策略:
一、精度失真的根本原因IEEE 754双精度浮点数的限制JavaScript的Number类型使用64位双精度浮点数存储所有数字,其中52位用于表示有效数字(尾数),11位用于指数,1位用于符号。这种结构决定了其整数精度范围:
最大安全整数:Number.MAX_SAFE_INTEGER(即2^53- 1,约9007199254740991)。
精度范围:整数部分超过16位(十进制)时,超出部分可能无法精确表示,导致后续位数显示错误。例如,输入17个连续的“1”时,实际存储的可能是近似值(如1.1111111111111111e+16),最终显示为11111111111111112。
科学计数法的隐式转换当数字过大时,JavaScript会自动将其转换为科学计数法(如1e+16),进一步加剧精度丢失。例如,11111111111111111会被存储为1.1111111111111111e+16,导致末尾数字失真。
二、调试方法通过在关键函数中插入console.log(),可以定位精度丢失的具体阶段。以简化版getDisplayNumber函数为例:
class Calculator{ getDisplayNumber(number){ console.log("内部存储的原始数字:", number);//检查数字是否已失真 const stringNumber= number.toString(); const integerDigits= parseFloat(stringNumber.split('.')[0]); console.log("解析出的整数部分:", integerDigits);//观察整数部分是否变化 let integerDisplay; if(isNaN(integerDigits)){ integerDisplay='';} else{ integerDisplay= integerDigits.toLocaleString('en',{ maximumFractionDigits: 0});} const decimalDigits= stringNumber.split('.')[1]; return decimalDigits? `${integerDisplay}.${decimalDigits}`: integerDisplay;}}调试输出示例:输入17个“1”时,控制台可能显示:
内部存储的原始数字: 1.1111111111111111e+16解析出的整数部分: 11111111111111112这表明数字在存储阶段已失真,后续解析和格式化无法恢复精度。
三、应对策略与最佳实践1.限制用户输入长度适用场景:基础计算器无需处理超大整数。实现方式:设定输入上限(如15-16位),阻止用户输入更多数字或弹出提示。优点:简单直接,避免精度问题。缺点:灵活性较低,不适用于需要大数计算的场景。2.使用BigInt类型(ES2020+)适用场景:需要精确表示任意大整数。实现方式:创建BigInt字面量:在数字后加n(如123n)。
转换函数:BigInt("9007199254740991")。
运算规则:所有参与运算的数字必须为BigInt类型,不能与Number混合运算。
示例代码:let num1= BigInt("9007199254740991");// MAX_SAFE_INTEGERlet num2= BigInt(2);let sum= num1+ num2;//结果为9007199254740993nconsole.log(sum.toString());//输出"9007199254740993"优点:精确表示任意大整数。缺点:不支持小数,且需确保所有运算使用BigInt类型。3.基于字符串的算术(任意精度小数)适用场景:需处理任意精度小数或在不支持BigInt的环境中运行。实现方式:将数字存储为字符串,手动实现加、减、乘、除等运算(模拟竖式计算)。
使用第三方库(如decimal.js或big.js)简化实现。
示例库用法(decimal.js):import Decimal from'decimal.js';let a= new Decimal("11111111111111111");let b= new Decimal("22222222222222222");let sum= a.plus(b);//结果为"33333333333333333"console.log(sum.toString());优点:支持任意精度小数,灵活性高。缺点:实现复杂,性能可能低于原生类型。四、总结JavaScript计算器的大数精度问题源于Number类型的浮点数表示限制。通过调试可定位问题阶段,而应对策略需根据需求选择:
基础需求:限制输入长度。大整数需求:使用BigInt。高精度小数需求:基于字符串或第三方库。合理选择策略可确保计算器在各种场景下提供可靠结果。
关于javascript简易计算器,js做简易计算器的介绍到此结束,希望对大家有所帮助。