大家好,我是工藤学编程 | 一个正在努力学习的小博主,期待你的关注 |
---|---|
作业侠系列最新文章 | JavaScript实现仿windows计算器 |
SpringBoot实战系列 | 【SpringBoot实战系列】AOP+自定义注解-接口防重提交多场景设计实战 |
环境搭建大集合 | 环境搭建大集合(持续更新) |
往期源码回顾:
【Java】实现绘图板(完整版)
【C++】图书管理系统(完整板)
【Java】实现计算器(完整版)
【Python】实现爬虫,爬取天气情况并进行分析(完整版)
【Java】实现记事本(完整版)
【Java】实现多线程计算阶乘和(完整版)
【Java】实现聊天程序(完整版)
本项目速览:
1.项目简介
2.效果图
3.项目功能模块划分
4.函数流程图
5.设计与实现
6.js与html源码
1.项目简介:
计算器是一个常用的工具,非常适用。也是程序设计中常见的编程题。本项目实现了一款由标准模式,科学模式,程序员模式所组成的计算器。本计算器不仅能够实现连续的输入并进行正确的运算,还设计了计算过程中的历史记录,进制转换(2,8,10,16进制间的相互转换),科学计算等功能,能适应不同屏幕并有良好的响应式设计。
标准模式
html
DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>标准-计算器title>
<link rel="stylesheet" href="css/common/common.css" />
<link rel="stylesheet" href="css/calculate.css" />
<link rel="stylesheet" href="./components//List/index.css" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
meta>
head>
<body>
<div class="menu" id="change">
<svg t="1656246646180" style="margin-right: 10px" class="icon" viewBox="0 0 1024 1024" version="1.1"
xmlns="http://www.w3.org/2000/svg" p-id="1276" width="24" height="24">
<path
d="M133.310936 296.552327l757.206115 0c19.781623 0 35.950949-16.169326 35.950949-35.950949 0-19.781623-15.997312-35.950949-35.950949-35.950949L133.310936 224.650428c-19.781623 0-35.950949 16.169326-35.950949 35.950949C97.359987 280.383 113.529313 296.552327 133.310936 296.552327z"
p-id="1277">path>
<path
d="M890.51705 476.135058 133.310936 476.135058c-19.781623 0-35.950949 16.169326-35.950949 35.950949 0 19.781623 16.169326 35.950949 35.950949 35.950949l757.206115 0c19.781623 0 35.950949-16.169326 35.950949-35.950949C926.467999 492.304384 910.298673 476.135058 890.51705 476.135058z"
p-id="1278">path>
<path
d="M890.51705 727.447673 133.310936 727.447673c-19.781623 0-35.950949 15.997312-35.950949 35.950949s16.169326 35.950949 35.950949 35.950949l757.206115 0c19.781623 0 35.950949-15.997312 35.950949-35.950949S910.298673 727.447673 890.51705 727.447673z"
p-id="1279">path>
svg>
<span>标准span>
div>
<div class="history-button">
<svg t="1656425516728" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
p-id="2222" width="24" height="24">
<path
d="M516.266667 554.666667L512 341.333333h42.666667v192l136.533333 136.533334-29.866667 29.866666-145.066666-145.066666z m-371.2-128l34.133333 34.133333C213.333333 294.4 358.4 170.666667 533.333333 170.666667c200.533333 0 362.666667 162.133333 362.666667 362.666666S733.866667 896 533.333333 896c-187.733333 0-341.333333-140.8-358.4-324.266667l55.466667 55.466667c38.4 132.266667 162.133333 226.133333 307.2 226.133333 174.933333 0 320-145.066667 320-320S708.266667 213.333333 533.333333 213.333333 213.333333 358.4 213.333333 533.333333v21.333334l-42.666666-42.666667-85.333334-85.333333h59.733334z"
fill="#444444" p-id="2223">path>
svg>
div>
<div class="main-container">
<table>
<thead>
<th colspan="4">
<input type="text" id="result" disabled>
th>
thead>
<tbody>
<tr>
<td><button class="operate" onclick="showNumber(this)">%button>td>
<td><button class="operate" id="clearError" onclick="clearResult()">CEbutton>td>
<td><button class="operate" onclick="clearOneResult()">←button>td>
<td><button class="operate" onclick="showNumber(this)">÷button>td>
tr>
<tr>
<td><button class="calculate" onclick="showNumber(this)">7button>td>
<td><button class="calculate" onclick="showNumber(this)">8button>td>
<td><button class="calculate" onclick="showNumber(this)">9button>td>
<td><button class="operate" onclick="showNumber(this)">xbutton>td>
tr>
<tr>
<td><button class="calculate" onclick="showNumber(this)">4button>td>
<td><button class="calculate" onclick="showNumber(this)">5button>td>
<td><button class="calculate" onclick="showNumber(this)">6button>td>
<td><button class="operate" onclick="showNumber(this)">-button>td>
tr>
<tr>
<td><button class="calculate" onclick="showNumber(this)">1button>td>
<td><button class="calculate" onclick="showNumber(this)">2button>td>
<td><button class="calculate" onclick="showNumber(this)">3button>td>
<td><button class="operate" onclick="showNumber(this)">+button>td>
tr>
<tr>
<td><button class="calculate" onclick="getPow()">x²button>td>
<td><button class="calculate" onclick="showNumber(this)">0button>td>
<td><button class="calculate" onclick="showNumber(this)">.button>td>
<td><button class="operate" id="equal" onclick="showAnswer()">=button>td>
tr>
tbody>
table>
<div class="prompt-box close">
<div class="shadow-box">div>
<div class="result-history">
<div class="history-title">历史记录div>
div>
div>
div>
<script src="./components/List/index.js">script>
<script src="js/calculate.js">script>
body>
html>
标准模式
JS
var result = new Array();
const ops = "+-x÷%";
const errorExpre = "表达式错误"
const overMax = "溢出";
function arrToStr(arr) {
let strResult = "";
for (let i = 0; i < arr.length; i++) {
strResult += arr[i];
}
return strResult;
}
function showResult() {
document.getElementById("result").value = arrToStr(result);
}
function showNumber(id) {
let val = id.innerHTML;
if (result.length < 15) {
result.push(val);
}
showResult();
}
function disabledButtons() {
document.querySelectorAll("button").forEach(button => {
button.disabled = true;
button.classList.add("button-disabled");
clearError.classList.remove("button-disabled");
clearError.disabled = "";
});
}
function showAnswer() {
let answer = "";
let str = arrToStr(result);
let midExpre = strToExpress(str);
let suffixExpre = midToSuffix(midExpre);
answer = suffixValue(suffixExpre);
if (isNaN(answer, 10)) {
result.splice(0, result.length);
answer = errorExpre;
disabledButtons();
} else if (answer === Number.POSITIVE_INFINITY) {
result.splice(0, result.length);
answer = overMax;
disabledButtons();
} else {
clearResult();
result.push(answer);
fillResultHistory(str + "=", answer);
}
document.getElementById("result").value = answer;
}
function clearResult() {
result = [];
showResult();
document.querySelectorAll("button").forEach(button => {
if ((button.disabled = "true")) {
button.disabled = "";
button.classList.remove("button-disabled");
}
});
}
function clearOneResult() {
result.pop();
showResult();
}
function strToExpress(str) {
let textArr = str.split("");
let newTextArr = [];
let calTextArr = [];
for (let i = 0; i < str.length; i++) {
if (
(i == 0 && str[i] == "-") ||
(str[i] == "-" && ops.indexOf(str[i - 1]) != -1)
) {
newTextArr.push(textArr[i]);
} else if (ops.indexOf(str[i]) != -1) {
newTextArr.push("|", str[i], "|");
} else {
newTextArr.push(textArr[i]);
}
}
calTextArr = newTextArr.join("").split("|");
return calTextArr;
}
function midToSuffix(midExpre) {
let opStack = [];
let suffixExpre = [];
for (let i = 0; i < midExpre.length; i++) {
if (ops.indexOf(midExpre[i]) != -1) {
if (
opStack.length == 0 ||
Priority(midExpre[i]) > Priority(opStack[opStack.length - 1])
) {
opStack.push(midExpre[i]);
} else {
do {
suffixExpre.push(opStack.pop());
} while (
opStack.length > 0 &&
Priority(midExpre[i]) <= Priority(opStack[opStack.length - 1])
);
opStack.push(midExpre[i]);
}
} else {
suffixExpre.push(midExpre[i]);
}
}
while (opStack.length > 0) {
suffixExpre.push(opStack.pop());
}
return suffixExpre;
}
function Priority(op) {
let opPri = 0;
switch (op) {
case "+":
opPri = 1;
break;
case "-":
opPri = 1;
break;
case "x":
opPri = 2;
break;
case "÷":
opPri = 2;
break;
case "%":
opPri = 2;
break;
}
return opPri;
}
function suffixValue(suffixExpre) {
let calStack = [];
console.log(suffixExpre);
for (let i = 0; i < suffixExpre.length; i++) {
if (ops.indexOf(suffixExpre[i]) != -1) {
let opRight = Number(calStack.pop());
if (calStack.length == 0) return errorExpre;
let opLeft = Number(calStack.pop());
let tmpResult = 0;
switch (suffixExpre[i]) {
case "+":
tmpResult = highPrecisionAdd(opLeft, opRight);
break;
case "-":
tmpResult = highPrecisionSubtr(opLeft, opRight);
break;
case "x":
tmpResult = highPrecisionMul(opLeft, opRight);
break;
case "÷":
tmpResult = highPrecisionDiv(opLeft, opRight);
break;
case "%":
tmpResult = opLeft % opRight;
}
calStack.push(tmpResult);
} else {
calStack.push(suffixExpre[i]);
}
console.log(calStack);
}
return calStack.pop();
}
function getPow() {
let temp = result.join("");
if (isNaN(Number(temp, 10))) {
result = [];
result.push(errorExpre);
showResult();
} else {
result = [];
temp = Number(temp);
result[0] = highPrecisionMul(temp, temp);
showResult();
fillResultHistory(temp + "x" + temp + "=", result[0]);
}
}
function fillResultHistory(processStr, resultStr) {
const precessDiv = document.createElement("div");
const resultDiv = document.createElement("div");
const calculateItem = document.createElement("div");
const resultHistory = document.querySelector(".result-history");
calculateItem.className = "calculate-item";
precessDiv.className = "process";
resultDiv.className = "result";
precessDiv.innerText = processStr;
resultDiv.innerText = resultStr;
calculateItem.appendChild(precessDiv);
calculateItem.appendChild(resultDiv);
resultHistory.insertBefore(calculateItem, resultHistory.children[1]);
}
function showNumber(id) {
let val = id.innerHTML;
if (result.length < 15) {
if (result[result.length - 1] == "." && val == ".") return;
result.push(val);
}
showResult();
}
function highPrecisionAdd(arg1, arg2) {
let r1, r2, m;
try {
r1 = arg1.toString().split(".")[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split(".")[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2))
return (arg1 * m + arg2 * m) / m
}
function highPrecisionDiv(arg1, arg2) {
let t1 = 0,
t2 = 0,
r1, r2;
try {
t1 = arg1.toString().split(".")[1].length
} catch (e) {}
try {
t2 = arg2.toString().split(".")[1].length
} catch (e) {}
r1 = Number(arg1.toString().replace(".", ""))
r2 = Number(arg2.toString().replace(".", ""))
return (r1 / r2) * Math.pow(10, t2 - t1);
}
function highPrecisionMul(arg1, arg2) {
let m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length
} catch (e) {}
try {
m += s2.split(".")[1].length
} catch (e) {}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
function highPrecisionSubtr(arg1, arg2) {
let r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split(".")[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2));
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
科学模式
HTML
DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>科学-计算器title>
<link rel="stylesheet" href="css/common/common.css" />
<link rel="stylesheet" href="css/science.css" />
<link rel="stylesheet" href="components/List/index.css" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
meta>
head>
<body>
<div class="menu" id="change">
<svg t="1656246646180" style="margin-right: 10px" class="icon" viewBox="0 0 1024 1024" version="1.1"
xmlns="http://www.w3.org/2000/svg" p-id="1276" width="24" height="24">
<path
d="M133.310936 296.552327l757.206115 0c19.781623 0 35.950949-16.169326 35.950949-35.950949 0-19.781623-15.997312-35.950949-35.950949-35.950949L133.310936 224.650428c-19.781623 0-35.950949 16.169326-35.950949 35.950949C97.359987 280.383 113.529313 296.552327 133.310936 296.552327z"
p-id="1277">path>
<path
d="M890.51705 476.135058 133.310936 476.135058c-19.781623 0-35.950949 16.169326-35.950949 35.950949 0 19.781623 16.169326 35.950949 35.950949 35.950949l757.206115 0c19.781623 0 35.950949-16.169326 35.950949-35.950949C926.467999 492.304384 910.298673 476.135058 890.51705 476.135058z"
p-id="1278">path>
<path
d="M890.51705 727.447673 133.310936 727.447673c-19.781623 0-35.950949 15.997312-35.950949 35.950949s16.169326 35.950949 35.950949 35.950949l757.206115 0c19.781623 0 35.950949-15.997312 35.950949-35.950949S910.298673 727.447673 890.51705 727.447673z"
p-id="1279">path>
svg>
<span>科学span>
div>
<div class="history-button">
<svg t="1656425516728" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
p-id="2222" width="24" height="24">
<path
d="M516.266667 554.666667L512 341.333333h42.666667v192l136.533333 136.533334-29.866667 29.866666-145.066666-145.066666z m-371.2-128l34.133333 34.133333C213.333333 294.4 358.4 170.666667 533.333333 170.666667c200.533333 0 362.666667 162.133333 362.666667 362.666666S733.866667 896 533.333333 896c-187.733333 0-341.333333-140.8-358.4-324.266667l55.466667 55.466667c38.4 132.266667 162.133333 226.133333 307.2 226.133333 174.933333 0 320-145.066667 320-320S708.266667 213.333333 533.333333 213.333333 213.333333 358.4 213.333333 533.333333v21.333334l-42.666666-42.666667-85.333334-85.333333h59.733334z"
fill="#444444" p-id="2223">path>
svg>
div>
<div class="main-container">
<table>
<thead>
<th colspan="5">
<input type="text" id="result" disabled>
th>
thead>
<tbody>
<tr>
<td><button class="operate" onclick="math(this)">∏button>td>
<td><button class="operate" onclick="math(this)">ebutton>td>
<td><button class="operate" onclick="clearOneResult()">←button>td>
<td><button id="clearError" class="operate" onclick="clearResult()">CEbutton>td>
<td><button class="operate" onclick="showBigNumber(this)">%button>td>
tr>
<tr>
<td><button class="operate" onclick="math(this)">|x|button>td>
<td><button class="operate" onclick="math(this)">sinbutton>td>
<td><button class="operate" onclick="math(this)">cosbutton>td>
<td><button class="operate" onclick="math(this)">tanbutton>td>
<td><button class="operate" onclick="showBigNumber(this)">÷button>td>
tr>
<tr>
<td><button class="operate" onclick="showBigNumber(this)">n!button>td>
<td><button class="calculate" onclick="showBigNumber(this)">7button>td>
<td><button class="calculate" onclick="showBigNumber(this)">8button>td>
<td><button class="calculate" onclick="showBigNumber(this)">9button>td>
<td><button class="operate" onclick="showBigNumber(this)">xbutton>td>
tr>
<tr>
<td><button class="operate" onclick="showBigNumber(this)">x^ybutton>td>
<td><button class="calculate" onclick="showBigNumber(this)">4button>td>
<td><button class="calculate" onclick="showBigNumber(this)">5button>td>
<td><button class="calculate" onclick="showBigNumber(this)">6button>td>
<td><button class="operate" onclick="showBigNumber(this)">-button>td>
tr>
<tr>
<td><button class="operate" onclick="math(this)">logbutton>td>
<td><button class="calculate" onclick="showBigNumber(this)">1button>td>
<td><button class="calculate" onclick="showBigNumber(this)">2button>td>
<td><button class="calculate" onclick="showBigNumber(this)">3button>td>
<td><button class="operate" onclick="showBigNumber(this)">+button>td>
tr>
<tr>
<td><button class="operate" onclick="math(this)">lnbutton>td>
<td><button class="calculate" onclick="showBigNumber(this)">0button>td>
<td><button class="calculate" onclick="showBigNumber(this)">.button>td>
<td><button class="operate" onclick="math(this)">1/xbutton>td>
<td><button class="operate" id="equal" onclick="showAnswer()">=button>td>
tr>
tbody>
table>
<div class="prompt-box close">
<div class="shadow-box">div>
<div class="result-history">
<div class="history-title">历史记录div>
div>
div>
div>
<script src="components/List/index.js">script>
<script src="js/science.js">script>
body>
html>
科学模式
JS
var result = new Array();
const ops = ["+", "-", "x", "÷", "%", "^"];
const oneOps = ["!"];
const errorExpre = "表达式错误";
const overMax = "溢出";
function arrToStr(arr) {
let strResult = "";
for (let i = 0; i < arr.length; i++) {
strResult += arr[i];
}
return strResult;
}
function showResult() {
document.getElementById("result").value = arrToStr(result);
}
function disabledButtons() {
document.querySelectorAll("button").forEach(button => {
button.disabled = true;
button.classList.add("button-disabled");
clearError.classList.remove("button-disabled");
clearError.disabled = "";
});
}
function showAnswer() {
let answer = "";
let str = arrToStr(result);
let midExpre = strToExpress(str);
let suffixExpre = midToSuffix(midExpre);
answer = suffixValue(suffixExpre);
if (isNaN(answer, 10)) {
result.splice(0, result.length);
answer = errorExpre;
disabledButtons();
} else if (answer === Number.POSITIVE_INFINITY) {
result.splice(0, result.length);
answer = overMax;
disabledButtons();
} else {
clearResult();
result.push(answer);
fillResultHistory(str + "=", answer);
}
document.getElementById("result").value = answer;
}
function clearResult() {
result = [];
showResult();
document.querySelectorAll("button").forEach(button => {
if ((button.disabled = "true")) {
button.disabled = "";
button.classList.remove("button-disabled");
}
});
}
function clearOneResult() {
result.pop();
showResult();
}
function strToExpress(str) {
let textArr = str.split("");
let newTextArr = [];
let calTextArr = [];
for (let i = 0; i < str.length; i++) {
if (
(i == 0 && str[i] == "-") ||
(str[i] == "-" && ops.indexOf(str[i - 1]) != -1)
) {
newTextArr.push(textArr[i]);
} else if (ops.indexOf(str[i]) != -1 || oneOps.indexOf(str[i]) != -1) {
newTextArr.push("|", str[i], "|");
} else {
newTextArr.push(textArr[i]);
}
console.log(newTextArr);
}
calTextArr = newTextArr.join("").split("|");
return calTextArr;
}
function midToSuffix(midExpre) {
let opStack = [];
let suffixExpre = [];
for (let i = 0; i < midExpre.length; i++) {
if (ops.indexOf(midExpre[i]) != -1) {
if (
opStack.length == 0 ||
Priority(midExpre[i]) > Priority(opStack[opStack.length - 1])
) {
opStack.push(midExpre[i]);
} else {
do {
suffixExpre.push(opStack.pop());
} while (
opStack.length > 0 &&
Priority(midExpre[i]) <= Priority(opStack[opStack.length - 1])
);
opStack.push(midExpre[i]);
}
} else {
suffixExpre.push(midExpre[i]);
}
}
while (opStack.length > 0) {
let temp = opStack.pop();
if (temp != "") {
suffixExpre.push(temp);
}
}
return suffixExpre;
}
function Priority(op) {
let opPri = 0;
switch (op) {
case "+":
opPri = 1;
break;
case "-":
opPri = 1;
break;
case "x":
opPri = 2;
break;
case "÷":
opPri = 2;
break;
case "%":
opPri = 2;
break;
case "^":
opPri = 3;
break;
}
return opPri;
}
function suffixValue(suffixExpre) {
let calStack = [];
let tmpResult = 0;
console.log(suffixExpre);
for (let i = 0; i < suffixExpre.length; i++) {
if (ops.indexOf(suffixExpre[i]) != -1) {
let opRight = Number(calStack.pop());
let opLeft = Number(calStack.pop());
switch (suffixExpre[i]) {
case "+":
tmpResult = highPrecisionAdd(opLeft, opRight);
break;
case "-":
tmpResult = highPrecisionSubtr(opLeft, opRight);
break;
case "x":
tmpResult = highPrecisionMul(opLeft, opRight);
break;
case "÷":
tmpResult = highPrecisionDiv(opLeft, opRight);
break;
case "%":
tmpResult = opLeft % opRight;
break;
case "^":
tmpResult = Math.pow(opLeft, opRight);
break;
}
calStack.push(tmpResult);
} else if (oneOps.indexOf(suffixExpre[i]) != -1) {
let n = Number(calStack.pop());
switch (suffixExpre[i]) {
case "!":
tmpResult = getFactorial(n);
break;
}
calStack.push(tmpResult);
} else if (suffixExpre[i] != "") {
calStack.push(suffixExpre[i]);
}
}
return calStack.pop();
}
function fillResultHistory(processStr, resultStr) {
const precessDiv = document.createElement("div");
const resultDiv = document.createElement("div");
const calculateItem = document.createElement("div");
const resultHistory = document.querySelector(".result-history");
calculateItem.className = "calculate-item";
precessDiv.className = "process";
resultDiv.className = "result";
precessDiv.innerText = processStr;
resultDiv.innerText = resultStr;
calculateItem.appendChild(precessDiv);
calculateItem.appendChild(resultDiv);
resultHistory.insertBefore(calculateItem, resultHistory.children[1]);
}
function showBigNumber(id) {
let val = id.innerHTML;
if (result.length < 32) {
if (result[result.length - 1] == "." && val == ".") return;
if (val === "x^y") {
result.push("^");
} else if (val === "n!") {
result.push("!");
} else {
result.push(val);
}
}
showResult();
}
function getFactorial(n) {
let res = 1;
for (let i = 1; i <= Math.abs(n); i++) {
res *= i;
}
return n >= 1 ? res : 0 - res;
}
function isAllNum() {
let temp = result.join("");
if (isNaN(Number(temp, 10)) || result.length === 0) {
return false;
}
return true;
}
function isErrorExper() {
result = [];
result.push(errorExpre);
showResult();
disabledButtons();
}
function math(id) {
let val = id.innerHTML;
let temp = result.join("");
if (val === "∏") {
result.push(Math.PI);
} else if (val === "e") {
result.push(Math.E);
} else if (val === "|x|") {
if (isAllNum()) {
clearResult();
result.push(Math.abs(Number(temp)));
fillResultHistory("abs(" + temp + ")=", result[0]);
} else {
isErrorExper();
}
} else if (val === "log") {
if (isAllNum()) {
clearResult();
result.push(Math.log10(Number(temp)));
fillResultHistory("log(" + temp + ")=", result[0]);
} else {
isErrorExper();
}
} else if (val === "ln") {
if (isAllNum()) {
clearResult();
result.push(Math.log(Number(temp)));
fillResultHistory("ln(" + temp + ")=", result[0]);
} else {
isErrorExper();
}
} else if (val === "sin") {
if (isAllNum()) {
clearResult();
let res = (Math.sin(Number(temp)))
if (Math.abs(res) < 1e-15) {
res = 0;
}
result.push(res);
fillResultHistory("sin(" + temp + ")=", result[0]);
} else {
isErrorExper();
}
} else if (val === "cos") {
if (isAllNum()) {
clearResult();
let res = Math.cos(Number(temp))
if (Math.abs(res) < 1e-16) {
res = 0;
}
result.push(res);
fillResultHistory("cos(" + temp + ")=", result[0]);
} else {
isErrorExper();
}
} else if (val === "tan") {
if (isAllNum()) {
clearResult();
let res = (Math.tan(Number(temp)))
if (Math.abs(res) < 1e-15) {
res = 0;
} else if (res >= 1 - 0.9) {
res = 1;
}
result.push(res);
fillResultHistory("tan(" + temp + ")=", result[0]);
} else {
isErrorExper();
}
} else if (val === "1/x") {
if (isAllNum() && temp != "0") {
clearResult();
result.push(highPrecisionDiv(1, Number(temp)));
fillResultHistory("1/" + temp + "=", result[0]);
} else {
isErrorExper();
}
} else {
isErrorExper();
}
showResult();
}
function highPrecisionAdd(arg1, arg2) {
let r1, r2, m;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m;
}
function highPrecisionDiv(arg1, arg2) {
let t1 = 0,
t2 = 0,
r1,
r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) {}
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e) {}
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
function highPrecisionMul(arg1, arg2) {
let m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length;
} catch (e) {}
try {
m += s2.split(".")[1].length;
} catch (e) {}
return (
(Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
Math.pow(10, m)
);
}
function highPrecisionSubtr(arg1, arg2) {
let r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
n = r1 >= r2 ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
程序员模式
HTML
DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>程序员-计算器title>
<link rel="stylesheet" href="css/common/common.css" />
<link rel="stylesheet" href="css/programmer.css" />
<link rel="stylesheet" href="components/List/index.css" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
meta>
head>
<body>
<div class="menu" id="change">
<svg t="1656246646180" style="margin-right: 10px" class="icon" viewBox="0 0 1024 1024" version="1.1"
xmlns="http://www.w3.org/2000/svg" p-id="1276" width="24" height="24">
<path
d="M133.310936 296.552327l757.206115 0c19.781623 0 35.950949-16.169326 35.950949-35.950949 0-19.781623-15.997312-35.950949-35.950949-35.950949L133.310936 224.650428c-19.781623 0-35.950949 16.169326-35.950949 35.950949C97.359987 280.383 113.529313 296.552327 133.310936 296.552327z"
p-id="1277">path>
<path
d="M890.51705 476.135058 133.310936 476.135058c-19.781623 0-35.950949 16.169326-35.950949 35.950949 0 19.781623 16.169326 35.950949 35.950949 35.950949l757.206115 0c19.781623 0 35.950949-16.169326 35.950949-35.950949C926.467999 492.304384 910.298673 476.135058 890.51705 476.135058z"
p-id="1278">path>
<path
d="M890.51705 727.447673 133.310936 727.447673c-19.781623 0-35.950949 15.997312-35.950949 35.950949s16.169326 35.950949 35.950949 35.950949l757.206115 0c19.781623 0 35.950949-15.997312 35.950949-35.950949S910.298673 727.447673 890.51705 727.447673z"
p-id="1279">path>
svg>
<span>程序员span>
div>
<div class="history-button">
<svg t="1656425516728" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
p-id="2222" width="24" height="24">
<path
d="M516.266667 554.666667L512 341.333333h42.666667v192l136.533333 136.533334-29.866667 29.866666-145.066666-145.066666z m-371.2-128l34.133333 34.133333C213.333333 294.4 358.4 170.666667 533.333333 170.666667c200.533333 0 362.666667 162.133333 362.666667 362.666666S733.866667 896 533.333333 896c-187.733333 0-341.333333-140.8-358.4-324.266667l55.466667 55.466667c38.4 132.266667 162.133333 226.133333 307.2 226.133333 174.933333 0 320-145.066667 320-320S708.266667 213.333333 533.333333 213.333333 213.333333 358.4 213.333333 533.333333v21.333334l-42.666666-42.666667-85.333334-85.333333h59.733334z"
fill="#444444" p-id="2223">path>
svg>
div>
<div class="main-container">
<table>
<thead>
<th colspan="5">
<input type="text" id="result" disabled>
th>
thead>
<tbody>
<tr>
<td class="system" colspan="5">
<span class="system-item"> HEXspan>
<span class="ml-2" id="HEX_value">0span>
td>
tr>
<tr>
<td class="system" colspan="5">
<span class="bl-blue system-item"> DECspan>
<span class="ml-2" id="DEC_value">0span>
td>
tr>
<tr>
<td class="system" colspan="5">
<span class="system-item"> OCTspan>
<span class="ml-2" id="OCT_value">0span>
td>
tr>
<tr>
<td class="system" colspan="5">
<span class="system-item"> BINspan>
<span class="ml-2" id="BIN_value">0span>
td>
tr>
<tr>
<td><button class="operate hex button-disabled" onclick="showMidNumber(this)" disabled>Abutton>td>
<td><button class="operate" onclick="showMidNumber(this)"><<button>td>
<td><button class="operate" onclick="showMidNumber(this)">>>button>td>
<td><button id="clearError" class="operate" onclick="clearResult()">CEbutton>td>
<td><button class="operate" onclick="clearOneResult()">←button>td>
tr>
<tr>
<td><button class="operate hex button-disabled" onclick="showMidNumber(this)" disabled>Bbutton>td>
<td><button class="operate" onclick="showMidNumber(this)">(button>td>
<td><button class="operate" onclick="showMidNumber(this)">)button>td>
<td><button class="operate" onclick="showMidNumber(this)">%button>td>
<td><button class="operate" onclick="showMidNumber(this)">÷button>td>
tr>
<tr>
<td><button class="operate hex button-disabled" onclick="showMidNumber(this)" disabled>Cbutton>td>
<td><button class="calculate oct" onclick="showMidNumber(this)">7button>td>
<td><button class="calculate dec" onclick="showMidNumber(this)">8button>td>
<td><button class="calculate dec" onclick="showMidNumber(this)">9button>td>
<td><button class="operate" onclick="showMidNumber(this)">xbutton>td>
tr>
<tr>
<td><button class="operate hex button-disabled" onclick="showMidNumber(this)" disabled>Dbutton>td>
<td><button class="calculate oct" onclick="showMidNumber(this)">4button>td>
<td><button class="calculate oct" onclick="showMidNumber(this)">5button>td>
<td><button class="calculate oct" onclick="showMidNumber(this)">6button>td>
<td><button class="operate" onclick="showMidNumber(this)">-button>td>
tr>
<tr>
<td><button class="operate hex button-disabled" onclick="showMidNumber(this)" disabled>Ebutton>td>
<td><button class="calculate" onclick="showMidNumber(this)">1button>td>
<td><button class="calculate oct" onclick="showMidNumber(this)">2button>td>
<td><button class="calculate oct" onclick="showMidNumber(this)">3button>td>
<td><button class="operate" onclick="showMidNumber(this)">+button>td>
tr>
<tr>
<td><button class="operate hex button-disabled" onclick="showMidNumber(this)" disabled>Fbutton>td>
<td><button class="calculate" onclick="showMidNumber(this)">0button>td>
<td><button class="calculate" onclick="showMidNumber(this)">Andbutton>td>
<td><button class="operate" onclick="showMidNumber(this)">Orbutton>td>
<td><button class="operate" id="equal" onclick="showAnswer()">=button>td>
tr>
tbody>
table>
<div class="prompt-box close">
<div class="shadow-box">div>
<div class="result-history">
<div class="history-title">历史记录div>
div>
div>
div>
<script src="components/List/index.js">script>
<script src="js/programmer.js">script>
body>
html>
程序员模式
JS
var result = new Array();
const ops = ["+", "-", "x", "÷", "%", ">>", "<<", "&", "|", ")", "("];
const errorExpre = "表达式错误";
const overMax = "溢出";
const SystemEnum = {
hex: "0x",
dec: "0",
oct: "0o",
bin: "0b"
}
let currentSystem = SystemEnum.dec;
const hexButtons = document.querySelectorAll(".hex");
const decButtons = document.querySelectorAll(".dec");
const octButtons = document.querySelectorAll(".oct");
const systems = document.querySelectorAll(".system");
const systemItems = document.querySelectorAll(".system-item");
const systemChange = {
init: () => {
[...hexButtons, ...decButtons, ...octButtons].forEach(button => {
if ((button.disabled = "true")) {
button.disabled = "";
button.classList.remove("button-disabled");
}
});
},
[SystemEnum['hex']]: () => {
[...hexButtons, ...decButtons, ...octButtons].forEach(button => {
if ((button.disabled = "true")) {
button.disabled = "";
button.classList.remove("button-disabled");
}
});
},
[SystemEnum['dec']]: () => {
[...hexButtons].forEach(button => {
button.classList.add("button-disabled");
button.disabled = true;
});
},
[SystemEnum['oct']]: () => {
[...hexButtons, ...decButtons].forEach(button => {
button.classList.add("button-disabled");
button.disabled = true;
});
},
[SystemEnum['bin']]: () => {
[...hexButtons, ...decButtons, ...octButtons].forEach(button => {
button.classList.add("button-disabled");
button.disabled = true;
});
}
}
systems.forEach((system, index) => {
system.addEventListener("click", e => {
[...systemItems].forEach(item => {
if (item.classList.contains("bl-blue")) {
item.classList.remove("bl-blue");
}
});
systemItems[index].classList.add("bl-blue");
systemChange.init();
if (index === 0) {
currentSystem = SystemEnum.hex;
} else if (index === 1) {
currentSystem = SystemEnum.dec;
if (systemChange[SystemEnum.dec] !== undefined) {
systemChange[SystemEnum.dec]();
}
} else if (index === 2) {
currentSystem = SystemEnum.oct;
if (systemChange[SystemEnum.oct] !== undefined) {
systemChange[SystemEnum.oct]();
}
} else if (index === 3) {
currentSystem = SystemEnum.bin;
if (systemChange[SystemEnum.bin] !== undefined) {
systemChange[SystemEnum.bin]();
}
}
});
});
function arrToStr(arr) {
let strResult = "";
for (let i = 0; i < arr.length; i++) {
strResult += arr[i];
}
return strResult;
}
function showResult() {
document.getElementById("result").value = arrToStr(result);
}
function disabledButtons() {
document.querySelectorAll("button").forEach(button => {
button.disabled = true;
button.classList.add("button-disabled");
clearError.classList.remove("button-disabled");
clearError.disabled = "";
});
}
function showAnswer() {
let answer = "";
let str = arrToStr(result);
let midExpre = strToExpress(str);
let suffixExpre = midToSuffix(midExpre);
answer = suffixValue(suffixExpre);
if (isNaN(answer, 10)) {
result.splice(0, result.length);
answer = errorExpre;
disabledButtons();
} else if (answer === Number.POSITIVE_INFINITY) {
result.splice(0, result.length);
answer = overMax;
disabledButtons();
} else {
result = [];
if (currentSystem == "0x") {
answer = parseInt(answer).toString(16).toUpperCase();
} else if (currentSystem == "0o") {
answer = parseInt(answer).toString(8);
} else if (currentSystem == "0b") {
answer = parseInt(answer).toString(2);
}
result.push(answer);
fillResultHistory(str + "=", answer);
}
document.getElementById("result").value = answer;
let currentSystemValue;
if (currentSystem == "0x") {
currentSystemValue = (currentSystem + answer.replace("-", "")) * 1
} else {
currentSystemValue = currentSystem + Math.abs(answer);
}
if (answer < 0) currentSystemValue = "-" + currentSystemValue * 1;
if (!isNaN(currentSystemValue * 1)) {
fillSystemValues(
parseInt(currentSystemValue * 1).toString(16).toUpperCase(), currentSystemValue * 1,
parseInt(currentSystemValue * 1).toString(8), parseInt(currentSystemValue * 1).toString(2));
}
}
function clearResult() {
result = [];
showResult();
document.querySelectorAll("button").forEach(button => {
if ((button.disabled = "true")) {
button.disabled = "";
button.classList.remove("button-disabled");
}
});
systemChange[currentSystem]();
fillSystemValues(0, 0, 0, 0);
}
function clearOneResult() {
result.pop();
showResult();
}
function strToExpress(str) {
let textArr = str.split("");
let newTextArr = [];
let calTextArr = [];
for (let i = 0; i < str.length; i++) {
if (
(i == 0 && str[i] == "-") ||
(str[i] == "-" && ops.indexOf(str[i - 1]) != -1)
) {
newTextArr.push(textArr[i]);
} else if (str[i] === ">" || str[i] === "<") {
newTextArr.push("$", str[i++], str[i], "$");
} else if (ops.indexOf(str[i]) != -1) {
newTextArr.push("$", str[i], "$");
} else {
newTextArr.push(textArr[i]);
}
}
calTextArr = newTextArr.join("").split("$");
return calTextArr;
}
function midToSuffix(midExpre) {
let opStack = [];
let suffixExpre = [];
for (let i = 0; i < midExpre.length; i++) {
if (
ops.indexOf(midExpre[i]) != -1 ||
midExpre[i] == "(" ||
midExpre[i] == ")"
) {
if (midExpre[i] == "(") {
opStack.push(midExpre[i]);
} else if (midExpre[i] == ")") {
do {
suffixExpre.push(opStack.pop());
} while (opStack[opStack.length - 1] != "(");
opStack.pop();
} else if (
opStack.length == 0 ||
Priority(midExpre[i]) > Priority(opStack[opStack.length - 1])
) {
opStack.push(midExpre[i]);
} else {
do {
suffixExpre.push(opStack.pop());
} while (
opStack.length > 0 &&
Priority(midExpre[i]) <= Priority(opStack[opStack.length - 1])
);
opStack.push(midExpre[i]);
}
} else {
let tempValue;
if (currentSystem == "0x") {
tempValue = (currentSystem + midExpre[i].replace("-", "")) * 1;
tempValue=midExpre[i].indexOf("-")!=-1 ? 0 - tempValue : tempValue;
} else {
tempValue = (currentSystem + Math.abs(midExpre[i] * 1)) * 1;
tempValue = midExpre[i] * 1 < 0 ? 0 - tempValue : tempValue;
}
suffixExpre.push(tempValue);
}
}
while (opStack.length > 0) {
let temp = opStack.pop();
if (temp != "") {
suffixExpre.push(temp);
}
}
return suffixExpre;
}
function Priority(op) {
let opPri = 0;
switch (op) {
case "&":
opPri = -1;
break;
case "|":
opPri = -1;
break;
case ">>":
break;
case "<<":
break;
case "+":
opPri = 1;
break;
case "-":
opPri = 1;
break;
case "x":
opPri = 2;
break;
case "÷":
opPri = 2;
break;
case "%":
opPri = 2;
break;
}
return opPri;
}
function suffixValue(suffixExpre) {
let calStack = [];
let tmpResult = 0;
console.log(suffixExpre);
for (let i = 0; i < suffixExpre.length; i++) {
if (ops.indexOf(suffixExpre[i]) != -1) {
let opRight = Number(calStack.pop());
let opLeft = Number(calStack.pop());
switch (suffixExpre[i]) {
case "+":
tmpResult = highPrecisionAdd(opLeft, opRight);
break;
case "-":
tmpResult = highPrecisionSubtr(opLeft, opRight);
break;
case "x":
tmpResult = highPrecisionMul(opLeft, opRight);
break;
case "÷":
tmpResult = Math.floor(highPrecisionDiv(opLeft, opRight));
break;
case "%":
tmpResult = opLeft % opRight;
break;
case ">>":
tmpResult = opLeft >> opRight;
break;
case "<<":
tmpResult = opLeft << opRight;
break;
case "|":
tmpResult = opLeft | opRight;
break;
case "&":
tmpResult = opLeft & opRight;
break;
}
calStack.push(tmpResult);
} else if (suffixExpre[i] != "") {
calStack.push(suffixExpre[i]);
}
}
console.log(calStack);
return calStack.pop();
}
function fillResultHistory(processStr, resultStr) {
const precessDiv = document.createElement("div");
const resultDiv = document.createElement("div");
const calculateItem = document.createElement("div");
const resultHistory = document.querySelector(".result-history");
calculateItem.className = "calculate-item";
precessDiv.className = "process";
resultDiv.className = "result";
precessDiv.innerText = processStr;
resultDiv.innerText = resultStr;
calculateItem.appendChild(precessDiv);
calculateItem.appendChild(resultDiv);
resultHistory.insertBefore(calculateItem, resultHistory.children[1]);
}
function showMidNumber(id) {
let val = id.innerText;
if (result.length < 16) {
if (val === "x^y") {
result.push("^");
} else if (val === "And") {
result.push("&");
} else if (val === "Or") {
result.push("|");
} else {
result.push(val);
}
}
showResult();
}
function isAllNum() {
let temp = result.join("");
if (isNaN(Number(temp, 10)) || result.length === 0) {
return false;
}
return true;
}
function isErrorExper() {
result = [];
result.push(errorExpre);
showResult();
disabledButtons();
}
function highPrecisionAdd(arg1, arg2) {
let r1, r2, m;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m;
}
function highPrecisionDiv(arg1, arg2) {
let t1 = 0,
t2 = 0,
r1,
r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) {}
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e) {}
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
function highPrecisionMul(arg1, arg2) {
let m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[1].length;
} catch (e) {}
try {
m += s2.split(".")[1].length;
} catch (e) {}
return (
(Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
Math.pow(10, m)
);
}
function highPrecisionSubtr(arg1, arg2) {
let r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
n = r1 >= r2 ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
function fillSystemValues(hex, dec, oct, bin) {
HEX_value.innerText = hex;
DEC_value.innerText = dec;
OCT_value.innerText = oct;
BIN_value.innerText = bin;
}
切换模式组件
JS
function createList() {
const node = document.createElement("div");
node.className = "list";
const listArray = [
{
title: "标准",
url: "http://127.0.0.1:8848/calculator/index.html",
icon: ``,
},
{
title: "科学",
url: "http://127.0.0.1:8848/calculator/science.html",
icon: ``,
},
{
title: "程序员",
url: "http://127.0.0.1:8848/calculator/programmer.html",
icon: ``,
},
];
const result = listArray
.map(
item =>
``
)
.join("");
node.innerHTML = result;
return node;
}
(function () {
const list = createList();
const body = document.querySelector("body");
body.insertBefore(list, body.children[0]);
change.addEventListener("click", () => {
if (list.style.width !== "250px") {
change.children[1].style.opacity = 0;
list.style.width = "250px";
} else {
change.children[1].style.opacity = 1;
list.style.width = 0;
}
});
const prompt = document.querySelector(".prompt-box");
if (prompt) {
document.querySelector(".shadow-box").addEventListener("click", () => {
if (prompt.classList.contains("open")) {
prompt.classList.replace("open", "close");
} else {
prompt.classList.add("close");
}
});
}
const historyButton = document.querySelector(".history-button");
historyButton.addEventListener("click", () => {
if (prompt.classList.contains("close")) {
prompt.classList.replace("close", "open");
} else {
prompt.classList.replace("open", "close");
}
});
})();