简易计算器js代码
js加减乘除运算代码
js加减乘除运算代码最近接到了一个新需求,要求实现一个动态的录入表单,这个表单绝大多数都是数字录入,并且其中的某些字段是有关联关系的。
例如三个字段 field1、field2、field3,它们的关系可能为:field3 = field1 + field2。
到时候后端会提供给你这个表达式,前端来自动计算。
你可能会想,没啥问题,监听 form 值变更,依赖字段变化了就把这个表达式里的字段名字符串替换成实际值,最后 eval 一下不就好了。
我一开始也确实是这么做的,但是 js 的精度问题给了我一脚:如果两个字段的值分别为 0.1 和 0.2,最后计算的结果将会为 0.。
这在这种数字表单录入里是不能接受的,单纯的乘100 最后除 100 也不靠谱,加上 eval 本身的不安全性,所以路还是要一步步的走。
现在回看上面的描述,我们可以把问题整理成下面这道题(完整实现见文末):consttemplateCalc = (template, values) => {}templateCalc('(val1 + val2) / val3', { val1: 1, val2: 2, val3: 2 });templateCalc('((val1 + val2) - val3 * val4) / val3', { val1: 1, val2: 2, val3: 2, val4: 10 }); templateCalc('val1 - val2', { val1: 0.3, val2: 0.2 }); templateCalc('(val1 + val2) / 10000', { val1: 100, val2: 5 });复制代码在精度问题上,我选择了 big.js - npm (npmjs) 来处理。
处理的整体思路如下:•把模板中的字段名和操作符拆开,即将字符串解析为token 数组•把 token 数组处理成逆波兰表达式•计算逆波兰表达式时将字段名替换为实际值并引入big.js 计算ok,接下来搞第一步:解析模板实现如下:const operatorReg = /[()+\-/* ]/g;exportconststrToToken = str => {const keys = str.split(operatorReg);const tokens = [];let temp = str;while (temp.length > 0) {if (keys.length > 0 &&temp.startsWith(keys[0])) {temp = temp.replace(keys[0], '');tokens.push(keys.shift());}else {tokens.push(temp[0]);temp = temp.substr(1);}}return tokens.filter(token => token && token !== ' ');}复制代码这里取了个巧,没有直接去解析模板,而且先用操作符把模板分隔开,这样剩下的就是操作数了,然后拿操作数去头部匹配模板,匹配上了就把这个操作数扔到最后队列里,没匹配上就说明是个操作符,把第一个字符扔队列里。
用java代码写的简易计算器(可以实现基本的加减乘除功能)
⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。
JS实现简易计算器的7种方法
JS实现简易计算器的7种⽅法先放图(好吧⽐较挫)⽅法⼀:最容易版<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value;}// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法⼆:结构和⾏为分离<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title>#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件// +btns[0].onclick = addHandler;// -btns[1].onclick = subtractHandler;// ×btns[2].onclick = multiplyHandler;// ÷btns[3].onclick = divideHandler;// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value; }// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法三:循环绑定事件<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;<!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件for (var i = 0; i < btns.length; i++) {btns[i].onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':subtractHandler();break;case 'multiply':multiplyHandler();break;case 'divide':divideHandler();break;}};}// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value; }// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法四:提取函数<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /> <input type="button" value="×" class="btn" title="multiply" /> <input type="button" value="÷" class="btn" title="divide" /> </p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件each(btns, function (index, elem ) {elem.onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':subtractHandler();break;case 'multiply':multiplyHandler();break;case 'divide':divideHandler();break;}};});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {sign.innerHTML = symbol;}// 加法function add(num1, num2) {return +num1 + +num2;}// 减法function subtract(num1, num2) {return num1 - num2;}// 乘法function multiply(num1, num2) {return num1 * num2;}// 除法function divide(num1, num2) {return num1 / num2;}// 输出结果}// 加function addHandler() {// sign.innerHTML = '+';updateSign('+');outputResult(add(formerInput.value, laterInput.value));}// 减function subtractHandler() {updateSign('-');outputResult(subtract(formerInput.value, laterInput.value)); }// 乘function multiplyHandler() {updateSign('×');outputResult(multiply(formerInput.value, laterInput.value)); }// 除function divideHandler() {updateSign('÷');outputResult(divide(formerInput.value, laterInput.value)); }</script></body></html>⽅法五:管理代码(找到组织)<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /> <input type="button" value="×" class="btn" title="multiply" /> <input type="button" value="÷" class="btn" title="divide" /> </p></div><script>// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'), btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':multiplyHandler();break;case 'divide':divideHandler();break;}};});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}var operation = {add: function(num1, num2) {return +num1 + +num2;},subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;}};// 输出结果function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}// 加function addHandler() {// sign.innerHTML = '+';updateSign('+');outputResult(operation.add(calculatorElem.formerInput.value, terInput.value));}// 减function subtractHandler() {updateSign('-');outputResult(operation.subtract(calculatorElem.formerInput.value, terInput.value)); }// 乘function multiplyHandler() {updateSign('×');outputResult(operation.multiply(calculatorElem.formerInput.value, terInput.value)); }// 除function divideHandler() {updateSign('÷');outputResult(operation.divide(calculatorElem.formerInput.value, terInput.value)); }</script></body></html>⽅法六:OCP开放--封闭原则<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /><input type="button" value="×" class="btn" title="multiply" /><input type="button" value="÷" class="btn" title="divide" /><input type="button" value="%" class="btn" title="mod" /><input type="button" value="^" class="btn" title="power" /><!-- <input type="button" value="1/x" class="btn" title="invert" /> --></p></div><script>// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'),btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {updateSign(this.value);outputResult(operate(this.title, calculatorElem.formerInput.value, terInput.value)); };});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}// 运算function operate(name, num1, num2) {if (!operation[name]) throw new Error('不存在名为' + name + '的运算⽅法!');return operation[name](num1, num2);}var operation = {add: function(num1, num2) {return +num1 + +num2;},subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;},addOperation: function (name, fn) {if (!this[name]) {this[name] = fn;}return this;}};operation.addOperation('mod', function (num1, num2) {return num1 % num2;}).addOperation('power', function (base, power) {return Math.pow(base, power);function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}</script></body></html>⽅法七:模块化<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /><input type="button" value="×" class="btn" title="multiply" /><input type="button" value="÷" class="btn" title="divide" /><input type="button" value="%" class="btn" title="mod" /><input type="button" value="^" class="btn" title="power" /><input type="button" value="1/x" class="btn" title="invert" /></p></div><script>(function () {// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'),btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {updateSign(this.value);outputResult(operate(this.title, calculatorElem.formerInput.value, terInput.value)); };});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}// 运算var operate = (function () {subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;},addOperation: function (name, fn) {if (!operation[name]) {operation[name] = fn;}return operation;}};function operate(name) {if (!operation[name]) throw new Error('不存在名为' + name + '的运算⽅法!');return operation[name].apply(operation, [].slice.call(arguments, 1, arguments.length)); }operate.addOperation = operation.addOperation;return operate;})();operate.addOperation('mod', function (num1, num2) {return num1 % num2;}).addOperation('power', function (base, power) {return Math.pow(base, power);}).addOperation('invert', function (num) {return 1 / num;});// 输出结果function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}})();</script></body></html>。
超级简易的JS计算器(实现加减乘除)
超级简易的JS计算器(实现加减乘除)<!DOCTYPE html><html><head><meta charset="UTF-8"><title>简单的计算器</title><style>body{margin: 0;}.tab{border: 3px solid black ;border-radius: 2px;border-collapse:collapse;width: 268px;height: 402px;margin: 100px auto;}.tr{height: 67px;width: 268px;border: 3px solid black ;text-align: right;}.tr1{width: 268px;height: 67px;border: 3px solid black ;text-align: center;}.tr2{width: 67px;height: 67px;border: 3px solid black ;text-align: center;}</style><script>var s1 = "";var s2 = "";var s3 = "";var s4 = "";var s5 = "";function view(val){var a = document.getElementById(val);s1 = a.innerHTML;if(s1=="+" || s1=="-" || s1=="*" || s1=="/"){s3 = s1;s1 = "";}if(s3=="+" || s3=="-" || s3=="*" || s3=="/"){add2(s1);}if(s3==""){add1(s1);}}function add1(s1){s2 = s2 + s1;show();}function add2(s1){s4 = s4 + s1;show();}function cal(){switch(s3){case "+":{s5 = (String)((parseFloat(s2)+parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}case "-":{s5 = (String)((parseFloat(s2)-parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}case "*":{s5 = (String)((parseFloat(s2)*parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}case "/":{s5 = (String)((parseFloat(s2)/parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}}}function show(){var result = document.getElementById("result");result.innerHTML = s2+s3+s4;}</script></head><body><table class="tab"><tr class = "tr2"><td colspan="4">简易计算器</td></tr><tr class="tr"><td id="result" colspan="4"></td></tr><tr ><td id="+" class="tr1" onclick="view('+')">+</td><td id="-" class="tr1" onclick="view('-')">-</td><td id="*" class="tr1" onclick="view('*')">*</td><td id="/" class="tr1" onclick="view('/')">/</td></tr><tr ><td id="7" class="tr1" onclick="view('7')">7</td><td id="8" class="tr1" onclick="view('8')">8</td><td id="9" class="tr1" onclick="view('9')">9</td><td id="0" class="tr1" onclick="view('0')">0</td></tr><tr><td id="4" class="tr1" onclick="view('4')">4</td><td id="5" class="tr1" onclick="view('5')">5</td><td id="6" class="tr1" onclick="view('6')">6</td><td id="." class="tr1" onclick="view('.')">.</td></tr><tr><td id="1" class="tr1" onclick="view('1')">1</td><td id="2" class="tr1" onclick="view('2')">2</td><td id="3" class="tr1" onclick="view('3')">3</td><td id="=" class="tr1" onclick="cal()">=</td></tr></table></body></html>对于这个程序来说,判断的顺序⾮常重要,不然就会把"+"号存在s2,s4中⽽不是s3中。
简易计算器代码
button[10] = new QPushButton(buttontext[10],this,buttontext[10]); // “—”
button[10]->setFixedSize(BUTTONWIDTH,BUTTONHEIGHT);
edit->setText(tr("%1").arg(0)); //这个函数可获取文本编辑框中光标的位置,并显示在状态栏中
//setText(tr(“%1行%2列”).arg(rowNum).arg(colNum));
initialize(); //调用初始化函数
}
void CWidget::initialize()
cwidget.cpp
#include "cwidget.h"
#define KEY_CLR "CLR"
#define KEY_ADD "+"
#define KEY_SUB "-"
#define KEY_MUL "*"
#define KEY_DIV "/"
#define KEY_EQ "="
#define KEY_0 "0"
{
delete edit;
delete *button;
delete mainLayout;
delete topLayout;
delete bottomLayout;
}
void CWidget::calculate() //响应按键“=”,调用计算功能
js中简单计算器的代码
js中简单计算器的代码JS中实现一个简单的计算器并不困难,我们只需利用基本的数学运算符和JavaScript的语法即可。
下面是一个实现加、减、乘、除四则运算的计算器的JavaScript代码示例:```javascript// 获取计算器的元素var calculator = document.getElementById('calculator'); // 获取数字、运算符和结果显示区域的元素var num1 = document.getElementById('num1');var num2 = document.getElementById('num2');var operator = document.getElementById('operator');var result = document.getElementById('result');// 给运算符按钮添加事件处理函数var addButton = document.getElementById('add');addButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 + n2;});var subtractButton =document.getElementById('subtract');subtractButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 - n2;});var multiplyButton =document.getElementById('multiply');multiplyButton.addEventListener('click', function() { var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 * n2;});var divideButton = document.getElementById('divide'); divideButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 / n2;});```在以上代码中,我们定义了四个函数来处理加、减、乘、除四则运算。
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()`函数将结果输出到屏幕上。
24点计算器的Javascript实现
24点计算器的Javascript实现前段时间⼩舅⼦(⼩学⽣)过来玩,没事⼀起玩3*8=24,遇到难算的半天都想不出来,所以就想有没有app或者⼩⼯具啥的,搜了⼀下,有⼯具,但是不好⽤,所以就想⾃⼰写个简单易⽤的。
开始着⼿做的时候,发现运算逻辑⽆法总结成简单的计算公式,百度也没找到有⼈完整的实现,最后只能⽤最笨的⽅法了,且听我娓娓道来。
⾸先,按照常规,共有四个正整数参与运算,取值区间均为 [1,10](包含1和10),仅有加减乘除以及括号运算,不存在其他⾼级运算(如平⽅、开⽅等等),这四个数的计算顺序不确定,每个数字参与且仅参与⼀次运算。
按数学的思路来对这个常规描述进⾏解析,如下:四个数 a、b、c、d ;取值范围 1<=a<=10,1<=b<=10,1<=c<=10,1<=d<=10;运算⽅式:+、 -、 *、 / 以及 () ;运算顺序不确定,所以我们暂时认为 a+b 、 b+a 、(a+b) 与 (b+a),a*b 、 b*a 、(a*b) 与(b*a) 等等均互为不相同的计算(⾄于把他们认为是相同的计算,还需要更深⼊的研究了,这⾥的愚笨算法暂时⽆法区分)。
我们先确定四个空位(美其名⽈ A、B、C、D),在计算的时候往这四个空位⾥填上这四个数字,如果按照我下⾯描述的计算⽅式最终得到24 ,那么我们就认为这种数字与计算的组合就是⼀种"3*8=24"的计算⽅法,否则,我们继续遍历。
我仔细思考了⼀下,这四个空位的结合顺序⼀共有 5 种:1、{[(A,B)C]D}2、{[A(B,C)]D}3、{A[(B,C)D]}4、{A[B(C,D)]}5、[(A,B),(C,D)]有了这些结合顺序之后,我们只需要把我们的四个数字分别放到这四个空位中,并且在这四个空位之间分别放上四种计算⽅式(+、 -、 *、 /)中的⼀种,然后根据这个组合计算出结果,并判断是否等于24,如果是,那么就找到了⼀种,否则继续往下执⾏。
eclipse实现简单计算器代码.
eclipse实现简单计算器代码.package Computer;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import java.util.LinkedList;import java.text.NumberFormat;public class Cacultor extends Frame implements ActionListener{/*** @param args*/NumberButton numberButton[];OperationButton operationButton[];Button 小数点按钮,正负号按钮,退格按钮,求倒数按钮,等号按钮,清零按钮;Panel panel;JTextField resultShow;String 运算符号[]={"+","-","*","/"};LinkedList 链表;boolean 是否按下等号=false;public Cacultor(){super("计算器");链表=new LinkedList();numberButton=new NumberButton[10];for(int i=0;i<=9;i++){numberButton[i]=new NumberButton(i);numberButton[i].addActionListener(this);}operationButton=new OperationButton[4];for(int i=0;i<4;i++){operationButton[i]=new OperationButton(运算符号[i]);operationButton[i].addActionListener(this);}小数点按钮=new Button(".");正负号按钮=new Button("+/-");等号按钮=new Button("=");求倒数按钮=new Button("1/x");退格按钮=new Button("退格");清零按钮=new Button("c");清零按钮.setForeground(Color.red);退格按钮.setForeground(Color.red);等号按钮.setForeground(Color.red);求倒数按钮.setForeground(Color.blue);正负号按钮.setForeground(Color.blue);小数点按钮.setForeground(Color.blue);退格按钮.addActionListener(this);清零按钮.addActionListener(this);等号按钮.addActionListener(this);小数点按钮.addActionListener(this);正负号按钮.addActionListener(this);求倒数按钮.addActionListener(this);resultShow=new JTextField(10);resultShow.setHorizontalAlignment(JTextField.RIGHT); resultShow.setForeground(Color.blue);resultShow.setFont(new Font("TimesRoman",Font.PLAIN,14)); resultShow.setBorder(newSoftBevelBorder(BevelBorder.LOWERED));resultShow.setBackground(Color.white);resultShow.setEditable(false);panel=new Panel();panel.setLayout(new GridLayout(4,5));panel.add(numberButton[1]);panel.add(numberButton[2]);panel.add(numberButton[3]);panel.add(operationButton[0]);panel.add(清零按钮);panel.add(numberButton[4]);panel.add(numberButton[5]);panel.add(numberButton[6]);panel.add(operationButton[1]);panel.add(退格按钮);panel.add(numberButton[7]);panel.add(numberButton[8]);panel.add(numberButton[9]);panel.add(operationButton[2]);panel.add(求倒数按钮);panel.add(numberButton[0]);panel.add(正负号按钮);panel.add(小数点按钮);panel.add(operationButton[3]);panel.add(等号按钮);add(panel,BorderLayout.CENTER);add(resultShow,BorderLayout.NORTH);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){ System.exit(0);}});setVisible(true);setBounds(100,50,240,180);setResizable(false);validate();}//按钮事件的处理public void actionPerformed(ActionEvent e){if(e.getSource() instanceof NumberButton){NumberButton b=(NumberButton)e.getSource();if(链表.size()==0){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);是否按下等号=false;}else if(链表.size()==1&&是否按下等号==false){ int number=b.getNumber();String num=(String)链表.getFirst();String s=num.concat(""+number);链表.set(0, s);resultShow.setText(s);}else if(链表.size()==1&&是否按下等号==true){int number=b.getNumber();链表.removeFirst();链表.add(""+number);是否按下等号=false;resultShow.setText(""+number);}else if(链表.size()==2){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);}else if(链表.size()==3){int number=b.getNumber();String num=(String)链表.getLast();String s=num.concat(""+number);链表.set(2, s);resultShow.setText(s);}}else if(e.getSource()instanceof OperationButton){ OperationButton b=(OperationButton)e.getSource();if(链表.size()==1){String fuhao=b.get运算符号();链表.add(fuhao);}else if(链表.size()==2){String fuhao=b.get运算符号();链表.set(1, fuhao);}else if(链表.size()==3){String fuhao=b.get运算符号();String number1=(String)链表.getFirst();String number2=(String)链表.getLast();String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}链表.clear();链表.add(""+n);链表.add(fuhao);resultShow.setText(""+n);}catch(Exception ee){}}}else if(e.getSource()==等号按钮){是否按下等号=true;if(链表.size()==1&&链表.size()==2){ String num=(String)链表.getFirst(); resultShow.setText(""+num);}else if(链表.size()==3){String number1=(String)链表.getFirst(); String number2=(String)链表.getLast(); String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}resultShow.setText(""+n);链表.set(0, ""+n);链表.removeLast();链表.removeLast();}catch(Exception ee){}}}else if(e.getSource()==小数点按钮){if(链表.size()==0){是否按下等号=false;}else if(链表.size()==1){String dot=小数点按钮.getLabel();String num=(String)链表.getFirst();String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(0, s);}else{s=num;}链表.set(0, s);resultShow.setText(s);}else if(链表.size()==3){String dot=小数点按钮.getLabel(); String num=(String)链表.getLast(); String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(2, s);}else{s=num;}resultShow.setText(s);}}else if(e.getSource()==退格按钮){if(链表.size()==1){String num=(String)链表.getFirst();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(0, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}else if(链表.size()==3){String num=(String)链表.getLast();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(2, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}}else if(e.getSource()==正负号按钮){if(链表.size()==1){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=-1*d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=-1*d;String str=String.valueOf(d);链表.set(2, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==求倒数按钮){if(链表.size()==1||链表.size()==2){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==清零按钮){是否按下等号=false;resultShow.setText("0");链表.clear();}}public static void main(String[] args) {// TODO Auto-generated method stub new Cacultor();}}。
最新js-cal网页简易计算器
除数字的输入为直接进行输入外,其他运算例如+、-、*、/、开平方等算法要求计算时通过内部较为复杂的运算将结果显示在显<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<td><input type="button" value=" 9 " onclick="getNum(9)"></td>
<td><input type="button" value=" * " onclick="getNum('*')"></td>
</tr>
<tr>
<td><input type="button" value=" 0 " onclick="getNum(0)"></td>
function getResult(){
var objresult2=document.getElementById("result");
//为结果赋值
objresult2.value=objresult2.value+"="+eval(objresult2.value);
clearContent=true;
<td width="23%"><input type="button" value=" 2 " onclick="getNum(2)"></td>
js+html实现简易网页计算器
js+html实现简易⽹页计算器前⾔很早之前就想⽤js写⼀个简单的计算器,今天这个⼼愿算是完成了,作为⽤js做的第⼀个⼩项⽬,挣扎了⼀下午,代码其实挺简单的,⽆奈本⼈太菜了,代码⼗分钟,bug半⼩时;图⽚展⽰其实第⼀张图才是我想做的计算器,但是最上⾯⼀⾏的功能⽆法实现,并且第⼀张是⽤grid布局写的,添加js不⽅便,于是我⼜写了第⼆张图的界⾯这个计算器的主要特点就是可以在屏幕上显⽰出⽤户想要计算的整个表达式,然后直接计算出结果,⽽不需要每进⾏⼀次加减乘除的运算都要按等于号;功能与界⾯是仿照的vivo⼿机⾃带的计算器,由于我⽤的就是vivo⼿机;html 部分1、第⼀张图⽚<div class="container"><input type="button" id="screen"><input type="button" id="mc" value="mc"><div id="m1"> m+</div><div id="m-"> m-</div><div id="mr"> mr</div><div id="ac">AC </div><div id="delete"><-</div><div id="bracket"> +/-</div><div id="chu"> ÷</div><div id="num7">7</div><div id="num8">8</div><div id="num9">9</div><div id="num4">4</div><div id="num5">5</div><div id="num6">6</div><div id="num1">1</div><div id="num2">2</div><div id="num3">3</div><div id="cheng">×</div><div id="num0">0</div><div id="spot">.</div><div id="add">+</div><div id="minus">-</div><div id="equal">=</div></div>2、第⼆张图⽚<body><table><tr><td colspan="4"><input class="screen" type="text" disabled /></td></tr><tr><td><input class="but_ac but" type="button" value="AC" style="color: orange"></td><td><input class="but_ac but" type="button" value="<—" style="color: orange"></td><td><input class="but" type="button" value="+/-"></td><td><input class="but" type="button" value="/"></td></tr><tr><td><input class="but" type="button" value="7"></td><td><input class="but" type="button" value="8"></td><td><input class="but" type="button" value="9"></td><td><input class="but" type="button" value="*"></td></tr><tr><td><input class="but" type="button" value="4"></td><td><input class="but" type="button" value="5"></td><td><input class="but" type="button" value="6"></td><td><input class="but" type="button" value="-"></td></tr><tr><td><input class="but" type="button" value="1"></td><td><input class="but" type="button" value="2"></td><td><input class="but" type="button" value="3"></td><td><input class="but" type="button" value="+"></td></tr><tr><td colspan="2"><input class="but" type="button" value="0" style="width: 180px"></td><td><input class="but" type="button" value="."></td><td><input class="but" type="button" value="=" style="background-color:orange ;color:white"></td></tr></table></body>html部分就是简单的⽤table写的,在单元格内嵌套按钮,为了和⼿机上的界⾯更像,AC、<-、=这三个按钮单独设置了字体颜⾊和背景颜⾊;eval函数在计算表达式的时候,只能识别乘号和除号只能识别*和/,⽽不是数学上的×和÷,因此,按钮修改了⼀下,下⾯的代码在⽹页打开之后,和上⾯的图⽚两个按钮有所不同;css部分第⼀张图⽚的.container{display: grid;width: 350px;height: 550px;grid-template-columns:repeat(4,25%); grid-template-rows:repeat(8,12.5%); background-color:lightgray;margin-top: 50px;text-align: center;line-height: 68.75px;font-size: 1.5em;}#screen{grid-column: 1/5;grid-row: 1/3;background-color: black;}#mc{grid-column: 1/2;grid-row: 3/4;border:solid 1px gray;border-left: 0px;font-size: 1.1em;background-color:lightgray;}#m1{grid-column: 2/3;grid-row: 3/4;border:solid 1px gray;border-left: 0px;}#m-{grid-column:3/4;grid-row: 3/4;border:solid 1px gray;border-left: 0px;}#mr{grid-column: 4/5;grid-row: 3/4;border:solid 1px gray;border-right: 0px;border-left: 0px;}#ac{grid-column:1/2;grid-row: 4/5;border:solid 1px gray;border-left: 0px;color: orange;border-top: 0px;}#delete{grid-column:2/3;grid-row: 4/5;border:solid 1px gray;border-left: 0px;color: orange;border-top: 0px;}#bracket{grid-column:3/4;grid-row: 4/5;border:solid 1px gray;border-left: 0px;border-top: 0px;}#chu{grid-column:4/5;grid-row: 4/5;border:solid 1px gray;border-left: 0px;border-top: 0px;border-right: 0px;}#num7{grid-column:1/2;grid-row: 5/6;border:solid 1px gray;border-left: 0px;}#num8{grid-column:2/3;grid-row: 5/6;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num9{grid-column:3/4;grid-row: 5/6;border:solid 1px gray; border-left: 0px;border-top: 0px;}#cheng{grid-column:4/5;grid-row: 5/6;border:solid 1px gray; border-left: 0px;border-top: 0px;border-right: 0px;}#num4{grid-column:1/2;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num5{grid-column:2/3;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num6{grid-column:3/4;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;}#minus{grid-column:4/5;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;border-right: 0px;}#num1{grid-column:1/2;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num2{grid-column:2/3;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num3{grid-column:3/4;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;}#add{grid-column:4/5;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;border-right: 0px;}#num0{grid-row: 8/9;border:solid 1px gray;border-left: 0px;border-top: 0px;}#spot{ grid-column:3/4;grid-row: 8/9;border:solid 1px gray;border-left: 0px;border-top: 0px;}#equal{grid-column:4/5;grid-row: 8/9;border:solid 1px gray;border-left: 0px;border-top: 0px;border-right: 0px;color: white;background-color: orange;}第⼆张图⽚的<style type="text/css">table{margin:0 auto; //使整个计算器的界⾯位于⽹页中央}.but_ac{width: 80px;height: 60px;background-color : lightgray; //设置按钮的背景颜⾊为浅灰⾊font-size: 1.2em; //设置字体⼤⼩}.but{width: 80px;height: 60px;background-color : lightgray;font-size: 1.2em;}.screen{width: 350px;height: 70px;font-size: 1.5em;color: white;background-color: black;text-align:right; //使⽤户输⼊的表达数从屏幕的右边开始显⽰}</style>js部分思路获取⽤户所点击的按钮上的元素将获取的元素显⽰在屏幕上调⽤eval函数计算表达式的结果整体就是⽤⼀连串的if else语句判断你所点击的按钮,然后作出回应代码<script type="text/javascript">window.onload=function(){var num=document.getElementsByClassName("but"); //num数组存放元素对象var scr=document.getElementsByClassName("screen")[0]; //获取屏幕对象for(var i=0;i<num.length;i++) //通过for循环为每个按钮添加onclick事件{num[i].onclick=function(){if(this.value=="AC"){ //如果点击AC,则清空屏幕scr.value="";}else if( this.value=="+/-"){ //如果点击“+/-”按钮有两种情况//第⼀种情况,如果此时屏幕为空,则什么也不显⽰if(scr.value==""){scr.value="";}//如果屏幕不为空,就判断最后两个元素是不是运算符加数字的结构else if(isNaN(scr.value.charAt(scr.value.length- 1))==false&&isNaN(scr.value.charAt(scr.value.length-2))==true) {//给最后⼀个数字加括号并变为负数}}//当屏幕不为空时,判断点击的是不是退格键else if (this.value=="<—"&&this.value!=""){//将最后⼀个元素截掉scr.value=scr.value.substr(0,scr.value.length-1);}//当屏幕为空时判断是否点击的是⼩数点else if(scr.value==""&&this.value=="."){scr.value="0.";}//当点击等于号时,⽤eval函数计算表达式的结果并显⽰到屏幕上else if(this.value=="="){scr.value=eval(scr.value);}//当屏幕为空时,点击+、-、*、/时不做反应else if(scr.value==""&&(this.value=="+"||this.value=="-"||this.value=="*"||this.value=="/")) {scr.value=="";}else{scr.value+=this.value;}}}}</script>完整代码<!DOCTYPE html><html><head><title>jsss</title><style type="text/css">table{margin:0 auto;}.but_ac{width: 80px;height: 60px;background-color : lightgray;font-size: 1.2em;}.but{width: 80px;height: 60px;background-color : lightgray;font-size: 1.2em;}.screen{width: 350px;height: 70px;font-size: 1.5em;color: white;background-color: black;text-align:right;}</style><script type="text/javascript">window.onload=function(){var result;var str=[];var num=document.getElementsByClassName("but");var scr=document.getElementsByClassName("screen")[0];for(var i=0;i<num.length;i++){num[i].onclick=function(){if(this.value=="AC"){scr.value="";}else if( this.value=="+/-"){if(scr.value==""){scr.value="";else if(isNaN(scr.value.charAt(scr.value.length-1))==false&&isNaN(scr.value.charAt(scr.value.length-2))==true) {scr.value=scr.value.substr(0,scr.value.length-1)+"("+"-"+scr.value.charAt(scr.value.length-1)+")";}}else if (this.value=="<—"&&this.value!=""){scr.value=scr.value.substr(0,scr.value.length-1);}else if(scr.value==""&&this.value=="."){scr.value="0.";}else if(this.value=="="){scr.value=eval(scr.value);}else if(scr.value==""&&(this.value=="+"||this.value=="-"||this.value=="*"||this.value=="/")){scr.value=="";}else{scr.value+=this.value;}}}}</script></head><body><table><tr><td colspan="4"><input class="screen" type="text" disabled /></td></tr><tr><td><input class="but_ac but" type="button" value="AC" style="color: orange"></td><td><input class="but_ac but" type="button" value="<—" style="color: orange"></td><td><input class="but" type="button" value="+/-"></td><td><input class="but" type="button" value="/"></td></tr><tr><td><input class="but" type="button" value="7"></td><td><input class="but" type="button" value="8"></td><td><input class="but" type="button" value="9"></td><td><input class="but" type="button" value="*"></td></tr><tr><td><input class="but" type="button" value="4"></td><td><input class="but" type="button" value="5"></td><td><input class="but" type="button" value="6"></td><td><input class="but" type="button" value="-"></td></tr><tr><td><input class="but" type="button" value="1"></td><td><input class="but" type="button" value="2"></td><td><input class="but" type="button" value="3"></td><td><input class="but" type="button" value="+"></td></tr><tr><td colspan="2"><input class="but" type="button" value="0" style="width: 180px"></td><td><input class="but" type="button" value="."></td><td><input class="but" type="button" value="=" style="background-color:orange ;color:white"></td></tr></table></body></html>。
java简易计算器完整代码
java简易计算器完整代码import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class Calculate extends JFrame implements ActionListener {/****/private static final long serialVersionUID = 1L;/*** @param args*/float userFloata=0f;float userFloatb=0f;double result;JLabel label1 ;JLabel label2;JLabel label3;JTextField textField1;JTextField textField2;JTextField textField3;JButton addButton;JButton subtractButton;JButton rideButton;JButton divideButton;public Calculate(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setTitle("简易计算器");JPanel viewJPanel_1=new JPanel();JPanel viewJPanel_2=new JPanel();addButton=new JButton("加");addButton.addActionListener(this);viewJPanel_1.add(addButton);subtractButton=new JButton("减");subtractButton.addActionListener(this);viewJPanel_1.add(subtractButton);rideButton=new JButton("乘");rideButton.addActionListener(this);viewJPanel_1.add(rideButton);divideButton=new JButton("除");divideButton.addActionListener(this);viewJPanel_1.add(divideButton);label1=new JLabel("数据1:");viewJPanel_2.add(label1);textField1=new JTextField(5);textField1.addActionListener(this);viewJPanel_2.add(textField1);label2=new JLabel("数据2:");viewJPanel_2.add(label2);textField2=new JTextField(5);textField2.addActionListener(this);viewJPanel_2.add(textField2);label3=new JLabel("结果是:");viewJPanel_2.add(label3 );textField3=new JTextField(5);viewJPanel_2.add(textField3);setSize(420,120);setVisible(true);validate();getContentPane().add(viewJPanel_1,BorderLayout.NORTH);getContentPane().add(viewJPanel_2,BorderLayout.CENTER);}public void CalculateEventHandel(){try{userFloata= Float.parseFloat(textField1.getText().trim());userFloatb= Float.parseFloat(textField2.getText().trim());} catch (NumberFormatException e) {JOptionPane.showMessageDialog(this, "请输入数字型数据!");textField1.setText("");textField1.requestFocus();textField2.setText("");textField3.setText("");return;}}public static void main(String[] args) { // TODO Auto-generated method stubnew Calculate();//a.CalculateEventHandel();}public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stubif(e.getSource()==addButton){this.CalculateEventHandel();result=userFloata+userFloatb;// System.out.println(""+result);textField3.setText(""+result);}else if(e.getSource()==subtractButton){ this.CalculateEventHandel();result=userFloata-userFloatb;textField3.setText(""+result);}else if(e.getSource()==rideButton){this.CalculateEventHandel();result=userFloata*userFloatb;textField3.setText(""+result);}else if(e.getSource()==divideButton){this.CalculateEventHandel();result=userFloata/userFloatb;textField3.setText(""+result);}}}。
html+js实现简单的计算器代码(加减乘除)
html+js实现简单的计算器代码(加减乘除)html+js实现简单的计算器代码(加减乘除)<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title></head><body><table><tr><td><input type="button" value="add" onclick="setOp('+', 'add');"/></td><td><input type="button" value="miner" onclick="setOp('-', 'miner');"/></td><td><input type="button" value="times" onclick="setOp('*', 'times');"/></td><td><input type="button" value="divide" onclick="setOp('/', 'divide');"/></td></tr></table><table id="tb_calc" style="display:none;"><tr><td> <input id="x" type="text" style="width:100px" value="" name="x" /></td><td> <lable id="op" name="op"></lable> </td><td> <input id="y" type="text" style="width:100px" value="" name="y" /> </td><td> <input id="opTips" type="button" value="" onclick="calc();"/> </td><td> <lable id="z" name="z"></lable> </td></tr></table><script type="application/javascript">function setOp(op, opTips){var tb=document.getElementById("tb_calc");tb.style.display = "none";document.getElementById("x").value = "";document.getElementById("y").value = "";document.getElementById("z").innerText = "";document.getElementById("op").innerText = op;document.getElementById("opTips").value = opTips;tb.style.display = "block";}function calc(){var x = parseInt(document.getElementById("x").value);var y = parseInt(document.getElementById("y").value);var op = document.getElementById("op").innerText;var z = "";switch(op){case '+':z = x + y;break;case '-':z = x - y;break;case '*': ;z = x * y;break;case '/': ;z = x / y;break;default:z = '';}console.log(x, op, y, '=', z);document.getElementById("z").innerText = z;}</script></body></html>截图如下:以上这篇html+js实现简单的计算器代码(加减乘除)就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
JavaScript实现计算器的四则运算功能
JavaScript实现计算器的四则运算功能⽬录⼀、需求 + 最终实现1. 需求2. 说明:利⽤了字符串(split、replace)和数组(splice)的⽅法。
3. 代码实现⼆、实现步骤1. 版本⼀:实现基础加减乘除2. 版本⼆:实现⾼位数的运算3. ⽀持多次的运算三、思考后端思维前端思维结束⼀、需求 + 最终实现注:只是前端实现1. 需求需求来源是因为有⼀个做嵌⼊式 C/C++的基友做了⼀个远程计算器。
需求是要求⽀持输⼊⼀个四则混合运算公式的字符串,返回计算后的结果。
想看看⽤ C/C++封装过的 JavaScript 如果要实现这样⼀个功能最终效果(⽂章后我会讨论这两种实现思路,还望各位看官可以提出⼀些优化⽅案以及建议之类的~)。
2. 说明:利⽤了字符串(split、replace)和数组(splice)的⽅法。
主要是⽤到字符串切分为数组的⽅法 split、以及数组中插⼊删除的⽅法 splice。
字符串正则 replace ⽅法是考虑到⽤户的输⼊习惯可能有所不同,例如 1+2*3/4与 3 * 7 + 229。
⽀持:基础四则运算 3+6*5/6-3;⼩数四则运算 3.14 + 6 * 5 / 6 - 3.5;⾼位四则运算 99 * 94 - 6.35 + 100 / 1024;多次四则运算 3 * 3 + 3 * 16 - 7 - 5 + 4 / 2 + 22;以上综合不⽀持:带括号的运算 1 * (2 - 3);其他数学运算3. 代码实现/*** js四则混合运算计算器功能实现(约20⾏+ ⾯条代码)* @param {string} str 输⼊的四则运算字符串* @return {number} 输出结果*/const calculator = (str) => {// 定义添加字符函数const add = (arr, symbol) => {let length = arr.length;while (length > 1) {arr.splice(length - 1, 0, symbol); // 在每⼀项后⾯添加对应的运算符length--;}return arr; // ⽬的是得到⼀个改变长度的数组}const array = add(str.replace(/\s*/g,"").split('+'), '+').map(it => add(it.split('-'), '-').map(it => add(it.split('*'), '*').map(it => add(it.split('/'), '/')))).flat(3);;// 先运算乘除法['*', '/'].map(it => {while (array.includes(it)) {const index = array.findIndex(o => o === it);index > 0 && it === '*' ? array.splice(index - 1, 3, (Number(array[index - 1]) * Number(array[index + 1]))) : array.splice(index - 1, 3, (Number(array[index - 1]) / Number(array[index + 1])));}})// 再执⾏加减法,即从左⾄右的计算while (array.length > 1) {array[1] === '+' ? array.splice(0, 3, (Number(array[0]) + Number(array[2]))) : array.splice(0, 3, (Number(array[0]) - Number(array[2])));}return Number(array[0]).toFixed(2);}如果对 ES6 语法还算熟悉的话,应该可以轻松阅读代码的。
JS实现计算器带三角函数根号
JS实现计算器带三角函数根号以下是一个使用JavaScript实现的计算器代码,它包含了三角函数、开方等功能。
总字数超过1200字,但是实际代码量并不多,请自行补充。
```javascript//获取页面元素const display = document.getElementById("display");const buttons = document.getElementsByClassName("btn");//绑定按钮事件for (let i = 0; i < buttons.length; i++)buttons[i].addEventListener("click", buttonClick);//按钮点击事件处理函数function buttonClick(event)const buttonValue = event.target.innerHTML;if (buttonValue === "=")calculate(;} else if (buttonValue === "C")clear(;} else if (buttonValue === "√")squareRoot(;} else if (buttonValue === "sin")sine(;} else if (buttonValue === "cos")cosine(;} elseappendValue(buttonValue);}//向显示屏追加内容function appendValue(value)display.value += value;//清空显示屏function cleadisplay.value = "";//计算结果function calculattryconst result = eval(display.value); // 使用eval计算表达式display.value = result.toFixed(4); // 结果四舍五入保留4位小数} catch (error)display.value = "Error";}//计算平方根function squareRootryconst result = Math.sqrt(eval(display.value));display.value = result.toFixed(4);} catch (error)display.value = "Error";}//计算正弦值function sintryconst result = Math.sin(eval(display.value) * (Math.PI / 180)); // 将角度转换为弧度display.value = result.toFixed(4);} catch (error)display.value = "Error";}//计算余弦值function cosintryconst result = Math.cos(eval(display.value) * (Math.PI / 180)); // 将角度转换为弧度display.value = result.toFixed(4);} catch (error)display.value = "Error";}```HTML部分:```html<!DOCTYPE html><html><head><title>Calculator</title><link rel="stylesheet" type="text/css" href="style.css"> </head><body><div id="calculator"><input type="text" id="display" readonly> <div id="buttons"><div class="row"><button class="btn">7</button><button class="btn">8</button><button class="btn">9</button><button class="btn">/</button></div><div class="row"><button class="btn">4</button><button class="btn">5</button><button class="btn">6</button><button class="btn">*</button></div><div class="row"><button class="btn">1</button><button class="btn">2</button><button class="btn">3</button><button class="btn">-</button></div><div class="row"><button class="btn">0</button><button class="btn">.</button><button class="btn">+</button><button class="btn">=</button></div><div class="row"><button class="btn">C</button><button class="btn">√</button> <button class="btn">sin</button> <button class="btn">cos</button> </div></div></div><script src="script.js"></script> </body></html>```CSS部分:```css#calculatorwidth: 200px;margin: 0 auto;padding: 20px;#displaywidth: 100%;margin-bottom: 10px;padding: 5px;font-size: 20px;.rowdisplay: flex;.buttonflex: 1;margin-right: 5px;padding: 10px;font-size: 16px;```请注意,这只是一个简单的示例,实际的计算器功能可能更加复杂,需要根据具体需求进行适当的修改和扩展。
网页计算器--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>。
简易计算器代码
<input type="button" value="-" name="b6" onClick="SetExp('-')">
</td>
<td>
<input type="button" value="*" name="b5" onClick="SetExp('*')">
</td>
</tr>
<tr align="center">
</td>
<td>
<input type="button" value="3" name="b3" onClick="SetExp('3')">
</td>
</tr>
<tr align="center">
<td>
<input type="button" value="4" onClick="SetExp('4')">
<td>
<input type="button" value="7" onClick="SetExp('7')">
</td>
<td>
Vue.js实现的计算器功能完整示例
Vue.js实现的计算器功能完整⽰例本⽂实例讲述了Vue.js实现的计算器功能。
分享给⼤家供⼤家参考,具体如下:1. HTML部分代码<!DOCTYPE html><html lang="en"><head><link rel="stylesheet" type="text/css" href="css/css.css" rel="external nofollow" ><script type="text/javascript" src="https:///vue/2.5.16/vue.min.js"></script><meta charset="UTF-8"><title>my-calculator</title></head><body><div id="calculator"><!--显⽰框--><input-box v-bind:input-show="inputShow"></input-box><btn-list><div @click="clearValue()" class=" btn-30 btn-radius color-red clear-marginleft">C</div><div class=" btn-30 btn-radius color-blue">+/-</div><div @click="inputValue('%')" class=" btn-30 btn-radius color-blue">%</div><div @click="backValue()" class=" btn-70 btn-radius color-red font-14">←</div><div @click="inputValue('7')" class=" btn-30 btn-radius clear-marginleft">7</div><div @click="inputValue('8')" class=" btn-30 btn-radius">8</div><div @click="inputValue('9')" class=" btn-30 btn-radius">9</div><div @click="squareValue()" class=" btn-30 btn-radius color-blue font-14">ײ</div><div @click="radicalValue()" class=" btn-30 btn-radius color-blue font-12">√</div><div @click="inputValue('4')" class=" btn-30 btn-radius clear-marginleft">4</div><div @click="inputValue('5')" class=" btn-30 btn-radius">5</div><div @click="inputValue('6')" class=" btn-30 btn-radius">6</div><div @click="inputValue('×')" class=" btn-30 btn-radius color-blue font-14">×</div><div @click="inputValue('÷')" class=" btn-30 btn-radius color-blue font-12">÷</div><div @click="inputValue('1')" class=" btn-30 btn-radius clear-marginleft">1</div><div @click="inputValue('2')" class=" btn-30 btn-radius">2</div><div @click="inputValue('3')" class=" btn-30 btn-radius">3</div><div @click="inputValue('+')" class=" btn-30 btn-radius color-blue font-14">+</div><div @click="inputValue('-')" class=" btn-30 btn-radius color-blue font-14">-</div><div @click="inputValue('0')" class=" btn-70 btn-radius clear-marginleft">0</div><div @click="inputValue('.')" class=" btn-30 btn-radius">.</div><div @click="calValue()" class=" btn-70 btn-radius color-red font-14">=</div></btn-list></div><script>var calculator = new Vue({el:'#calculator',data:{inputShow:{value:'0'}},components:{'input-box':{props:['inputShow'],computed: {value:function () {return this.inputShow.value}},template:'<input id="input-box" type="text" size="21" maxlength="21" v-model="value" readonly="readonly">'},'btn-list':{template:'<div id="btn-list"><slot></slot></div>'}},methods:{inputValue(param){if(Object.prototype.toString.call(this.inputShow.value) == "[object Number]"){ //判断输⼊框内容是否为数字类型this.inputShow.value = "0"; //数字类型说明是上个计算结果,清空内容}var str ='' + this.inputShow.value; //输⼊内容时,将输⼊框内容转为字符串类型var len = str.length;var arr = ["+","-","×","÷"];var num = (''+parseFloat(str.split('').reverse().join(''))).split('').reverse().join(''); //parseInt(str.split('').reverse().join('')))是获取输⼊框内最后⼀串数字,再反转回来 ,num为输⼊框内最后⼀串数字 var nlen = num.length;if((num!= '0' && param != '.')|| (param == '.'&& num.indexOf(".")==-1)){ //输⼊框内最后⼀串数字不为0时拼接字符串if(arr.indexOf(str.charAt(len-1)) != -1 && arr.indexOf(param) != -1){ //若⼀开始输⼊内容为运算符,输⼊⽆效return;}this.inputShow.value += param; //拼接输⼊内容}else{arr.push("%");if(param == '.'){ //若num中已有⼩数点,输⼊内容为⼩数点,视为⽆效return;}else if(!(arr.indexOf(param) != -1)){ //判断输⼊框内最后⼀个字符不为运算符this.inputShow.value =str.substring(0,str.length-nlen) + param; //输⼊框内最后⼀串数字为0时,删除0拼接}}},clearValue(){ //清空输⼊框内容this.inputShow.value = '0';},calValue(){ //计算结果var str = this.inputShow.value;str = str.replace('×','*').replace('÷','/').replace('%','*0.01'); //替换运算符try{this.inputShow.value = eval(str); //若⽤户输⼊内容不符合运算规则,不计算}catch(error){return;}},squareValue(){ //平⽅计算var str = this.inputShow.value;this.inputShow.value = Math.pow(eval(str),2)},radicalValue(){ //开根号计算var str = this.inputShow.value;this.inputShow.value = Math.sqrt(eval(str));},backValue(){ //删除键,删除单个字符var str = this.inputShow.value;if(str.length == 1){this.inputShow.value = "0";}else{this.inputShow.value = str.slice(0,str.length-1);}},/*oppositeValue(){ //正负号取值var str = this.inputShow.value;var num = (''+parseInt(str.split('').reverse().join(''))).split('').reverse().join(''); //获取输⼊框内最后遗传数字var nlen = num.length;debugger;if(!isNaN( parseInt(str.charAt(str.length-1))) && num != 0){ //当输⼊框末位字符为数字且最后⼀串数字不为0时,取正负this.inputShow.value = str.substring(0,str.length-nlen)+`(-${num})`;}}*/}})</script></body></html>2. CSS部分代码@charset "utf-8";body, ul, dl, dd, dt, ol, li, p, h1, h2, h3, h4, h5, h6, textarea, form, select, fieldset, table, td, div, input{margin:0;padding:0;-webkit-text-size-adjust:none}h1, h2, h3, h4, h5, h6{font-size:12px;font-weight:normal}body>div{margin:0 auto}div{text-align:left}a img{border:0}body{color:#333;text-align:center;font:12px "微软雅⿊";}ul, ol, li{list-style-type:none;vertical-align:0}a{outline-style:none;color:#535353;text-decoration:none}a:hover{color:#D40000;text-decoration:none}.clear{height:0;overflow:hidden;clear:both}/* calculator */#calculator{width:200px;height:245px;padding:10px;border:1px solid #e5e5e5;background:#f8f8f8;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;box-shadow:0px 0px 10px #f2f2f2;-moz-box-shadow:0px 0px 10px #f2f2f2;-webkit-box-shadow:0 #calculator #input-box{margin:0;width:187px;padding:9px 5px;height:14px;border:1px solid #e5e5e5;border-radius:3px;-webkit-border-radius:3px;-moz-border-radius:3px;background:#FFF;text-align:right;line-height:14px;font-size:12px;font-family:Verdana, Geneva #calculator #btn-list{width:200px;overflow:hidden;}#calculator #btn-list .btn-radius{border-radius:2px;-webkit-border-radius:2px;-moz-border-radius:2px;border:1px solid #e5e5e5;background:-webkit-gradient(linear, 0 0, 0 100%, from(#f7f7f7), to(#ebebeb));background:-moz-linear-gradient(top, #f7f7f7,#ebebeb);filter #calculator #btn-list .btn-radius:active{background:#ffffff;}#calculator #btn-list .clear-marginleft{margin-left:0;}#calculator #btn-list .font-14{font-size:14px;}#calculator #btn-list .color-red{color:#ff5050}#calculator #btn-list .color-blue{color:#00b4ff}#calculator #btn-list .btn-30{width:29px;height:29px;}#calculator #btn-list .btn-70{width:70px;height:29px;}4. 使⽤时记得改下css路径,在html中引⼊vue5. 博主技术有限,正负号部分功能还有问题待完善.计算器还有⼀些未知的⼩Bug,感兴趣的读者可以在这个基础上进⾏扩展。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
<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;
/*big样式*/
.box{width:470px;height:482px;margin:0 auto;}
.box2{width:420px;height:440px;background:#dddddd;border:1px solid red;margin:14px 26px 14px 26px;}
</form>
<ul>
<li onclick="gei>
<li onclick="getNum(8)">8</li>
<li onclick="getNum(9)">9</li>
<li onclick="getDel()">←</li>
<li onclick="getClean()">C</li>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/1999/xhtml">
{
oinp.value ="";//如果是的oinp.value自动设置为0
}
oinp.value = oinp.value +x;//将获取的数字链接起来
}
function getFh(y)
{
//先获取当前的value值
num = Number(oinp.value);//将oinp.value转换为数字
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
/*全局样式*/
body{ padding:0; margin:0; font-size:12px; background:url("../images/body_bg.jpg") repeat-x;background-color:#fff;font-family:"宋体";}
if(temp == "" || temp =='0')//判断截取的剩下字符串是不是为空或者为零;
{
temp = 0;
}
oinp.value=temp ;//如果不是为空直接将剩下的字符串传到oinp.value里面;
}
//小数点运算还没有加进去,如有需要自己添加
</script>
</body>
</html>
ul,li,dl,dt,dd,h1,h2,h3,h4,h5,h6,form,p { padding:0; margin:0;}
ul{list-style:none;}
img{border:0px;}
.clearfloat{clear:both; height:0px; font-size:1px; line-height:0px;}
<!--alert(num1);-->
switch(fh)
{
case '+' :result = num + num1;break;
case '-' :result = num - num1;break;
case '*' :result = num * num1;break;
case '/' :result = num / num1;break;
fh = y; //存取符号
<!--alert(fh);-->
oinp.value = "";//当符号存取后自动清除oinp.value值
<!-- alert(num);-->
}
function jisuanqi()
{
var result = 0;//设置局部变量result;
var num1 = Number(oinp.value);//存取第二次输入的数字
.box2 h3{font-size:18px;font-weight:bold;margin-left:20px;margin-top:15px;}
.box2 input{width:385px;height:45px;margin-left:14px;}
.box2 ul{width:380px;height:205px;float:left;padding-left:16px;padding-top:20px;}
.box2 ul li.li3{width:134px;}
</style>
</head>
<body>
<div class="box">
<div class="box2" id="box2">
<h3>计算器</h3>
<form id="aa">
<input type="text" value="0" id="inp" />
.box2 ul li{width:58px;height:50px;background:#33ff00;float:left;margin-right:18px;margin-bottom:20px;line-height:50px;text-align:center;}
input{text-align:right;}
var oinp = document.getElementById('inp');//设置全局变量获取input框
var num = 0;//设置全局变量存取第一个数字
var fh;//设置存取符号的全局变量
function getNum(x)
{
if(oinp.value == ''||oinp.value == 0)//先判断oinp.value是不是为空或者为0
<li onclick="getNum(4)">4</li>
<li onclick="getNum(5)">5</li>
<li onclick="getNum(6)">6</li>
<li onclick="getFh('+')">+</li>
<li onclick="getFh('-')">-</li>