简体   繁体   English

连续按下多个运算符时,如何防止计算器运算符修改结果? JavaScript

[英]How to prevent a calculator operator from modifying the result when multiple operators are pressed in a row? JavaScript

Creating a calculator with JavaScript, however if a user were to accidentally push an operator twice in a row, it would modify the result again based on the current values of a and b .使用 JavaScript 创建计算器,但是如果用户不小心连续两次按下运算符,它将根据ab的当前值再次修改结果。 This is primarily an issue if a user were to press the equal operator after entering an operation and then push another operator to add/subtract/etc.这主要是一个问题,如果用户在输入操作后按等号运算符,然后按另一个运算符进行加/减/等。 another number.另一个号码。

I am wondering if there is a way to prevent this from happening...the most logical thing I can think of would be if the operator button didn't modify the display or variables only when any two operator buttons are pressed twice in a row, though I have no idea how I would code that, and I would still need the operator to change the value of o .我想知道是否有办法防止这种情况发生......我能想到的最合乎逻辑的事情是,如果操作员按钮只有在连续按下任意两个操作员按钮时才修改显示或变量,虽然我不知道如何编写代码,但我仍然需要操作员更改o的值。

Alternative solutions are welcome as well.也欢迎替代解决方案。 FYI I am very new to programming so I may not understand complex solutions without a good amount of explanation.仅供参考,我对编程很陌生,所以如果没有大量的解释,我可能无法理解复杂的解决方案。

JS code: JS代码:

let clearBtn = document.getElementById('clearBtn');
let posNegBtn = document.getElementById('posNegBtn');
let divideBtn = document.getElementById('divideBtn');
let multiplyBtn = document.getElementById('multiplyBtn');
let subtractBtn = document.getElementById('subtractBtn');
let addBtn = document.getElementById('addBtn');
let equalBtn = document.getElementById('equalBtn');
let zero = document.getElementById('zero');
let decimalBtn = document.getElementById('decimalBtn');
let one = document.getElementById('one');
let two = document.getElementById('two');
let three = document.getElementById('three');
let four = document.getElementById('four');
let five = document.getElementById('five');
let six = document.getElementById('six');
let seven = document.getElementById('seven');
let eight = document.getElementById('eight');
let nine = document.getElementById('nine');
let display = document.getElementById('display');

let a = 0;
let b = 0;
let o = '-';
let currentNum;
let appendable = true;

clearBtn.addEventListener('click', clearDisplay);
posNegBtn.addEventListener('click', changePosNeg);
divideBtn.addEventListener('click', dividePressed);
multiplyBtn.addEventListener('click', multiplyPressed);
subtractBtn.addEventListener('click', subtractPressed);
addBtn.addEventListener('click', addPressed);
equalBtn.addEventListener('click', equalPressed);
zero.addEventListener('click', displayZero);
decimalBtn.addEventListener('click', displayDec);
one.addEventListener('click', display1);
two.addEventListener('click', display2);
three.addEventListener('click', display3);
four.addEventListener('click', display4);
five.addEventListener('click', display5);
six.addEventListener('click', display6);
seven.addEventListener('click', display7);
eight.addEventListener('click', display8);
nine.addEventListener('click', display9);

function clearDisplay() {
    display.value = '0';
    a = 0;
    b = 0;
    currentNum = display.value;
}

function displayZero() {
    if (appendable === true) {
        display.value += '0';
        currentNum = display.value;
    } else {
        display.value = 0;
    }
    appendable = true;
}

function displayDec() {
    if (appendable === true) {
        if (display.value.includes('.')) {
            display.value;
        } else {
            display.value += '.';
        }   
        currentNum = display.value;
    } else {
        display.value = '0.';
        appendable = true;
    }
}

function changePosNeg() {
    parseFloat(display.value *= -1);
    currentNum = display.value;
}

function display1() {
    if (display.value == '0' || appendable === false) {
        display.value ='1';
    } else {
        display.value += '1';
    } 
    currentNum = display.value;
    appendable = true;
}

function display2() {
    if (display.value == '0' || appendable === false) {
        display.value ='2';
    } else {
        display.value += '2';
    } 
    currentNum = display.value;
    appendable = true;
}

function display3() {
    if (display.value == '0' || appendable === false) {
        display.value ='3';
    } else {
        display.value += '3';
    } 
    currentNum = display.value;
    appendable = true;
}

function display4() {
    if (display.value == '0' || appendable === false) {
        display.value ='4';
    } else {
        display.value += '4';
    } 
    currentNum = display.value;
    appendable = true;
}

function display5() {
    if (display.value == '0' || appendable === false) {
        display.value ='5';
    } else {
        display.value += '5';
    } 
    currentNum = display.value;
    appendable = true;
}

function display6() {
    if (display.value == '0' || appendable === false) {
        display.value = '6';
    } else {
        display.value += '6';
    } 
    currentNum = display.value;
    appendable = true;
}

function display7() {
    if (display.value == '0' || appendable === false) {
        display.value = '7';    
    } else {
        display.value += '7';
    } 
    currentNum = display.value;
    appendable = true;
}

function display8() {
    if (display.value == '0' || appendable === false) {
        display.value = '8';
    } else {
        display.value += '8';
    } 
    currentNum = display.value;
    appendable = true;
}

function display9() {
    if (display.value == '0' || appendable === false) {
        display.value = '9';
    } else {
        display.value += '9';
    } 
    currentNum = display.value;
    appendable = true;
}

function addPressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '+';
    appendable = false;
}

function subtractPressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '-';
    appendable = false;
}

function multiplyPressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '*';
    appendable = false;
}

function dividePressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '/';
    appendable = false;
}

function equalPressed() {
    b = parseFloat(`${currentNum}`);
    operate();
}

function add() {
    display.value = a + b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function subtract() {
    result = 
    display.value = a - b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function multiply() {
    display.value = a * b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function divide() {
    display.value = a / b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function operate() {
    if (o == '-') {
        return subtract();
    } else if (o == '+') {
        return add();
    } else if (o == '*') {
        return multiply();
    } else if (o == '/') {
        return divide();
    }
}

HTML code: HTML 代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Calculator</title>
        <link rel="stylesheet" href="style.css">
        <script src="script.js" defer></script>
    </head>

    <body>
        <div class="container">
            <div id="calculator">
                <input id="display" type="text" value="0">
                <div id="buttons">
                    <div id="mainBtns">
                        <div id="otherBtns">
                            <button id="clearBtn">AC</button>
                            <button id="posNegBtn">+/-</button>
                        </div>
                        <div id="numBtns">
                            <button id="seven">7</button>
                            <button id="eight">8</button>
                            <button id="nine">9</button>
                            <button id="four">4</button>
                            <button id="five">5</button>
                            <button id="six">6</button>
                            <button id="one">1</button>
                            <button id="two">2</button>
                            <button id="three">3</button>
                            <button id="zero">0</button>
                            <button id="decimalBtn">.</button>
                        </div>
                    </div>
                    <div id="operators">
                        <button id="divideBtn">/</button>
                        <button id="multiplyBtn">x</button>
                        <button id="subtractBtn">-</button>
                        <button id="addBtn">+</button>
                        <button id="equalBtn">=</button>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

CSS code: CSS 代码:

.container {
    display: flex;
    flex-direction: column;
}

#calculator {
    display: flex;
    flex-direction: column;
    width: 200px;
    height: 330px;
    border: 15px solid black;
    background-color: black;
    gap: 20px;
}

#display {
    background-color: gray;
    height: 60px;
    text-align: right;
    font-size: 50px;
}

#buttons {
    display: flex;
    flex-direction: row;
    gap: 10px;
    align-items: center;
}

#operators {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

#divideBtn, #multiplyBtn, #subtractBtn, #addBtn, #equalBtn {
    width: 40px;
    height: 40px;
    background-color: chartreuse;
}

#mainBtns {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

#numBtns {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
    gap: 10px 10px;
}

#otherBtns {
    display: flex;
    gap: 10px;
    justify-content: space-around;
}
 
#nine, #eight, #seven, #six, #five, #four, #three, #two, #one, 
#decimalBtn, #posNegBtn {
    width: 40px;
    height: 40px;
} 

#zero, #clearBtn {
    width: 93px;
}

#clearBtn, #posNegBtn {
    background-color: aqua;
}

Store a variable that is a reference to the last button pressed, then in your operate function call a function that checks if the last button pressed is an operator and if it is then return early before the operation takes place.存储一个变量,该变量是对最后按下的按钮的引用,然后在您的操作函数中调用一个函数,该函数检查最后按下的按钮是否是操作符,以及是否在操作发生之前提前返回。

like this:像这样:

 let lastButtonPressed; function anyOfYourOperatorFunctions() { if (lastButtonPressedIsOperator(lastButtonPressed)) return null; else { ... } } function lastButtonPressedIsOperator(lastButton) { ... return true; } function operate() { if (lastButtonPressedIsOperator(lastButtonPressed)) return null; if (o == '-') { return subtract(); } else if (o == '+') { return add(); } else if (o == '*') { return multiply(); } else if (o == '/') { return divide(); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM