Resultados errados na calculadora

HTML

JavaScript

14/02/2023

Olá pessoal, estou fazendo uma calculadora em Html, css e Javascript, consegui implementar o código. Mas os resultados vem completamente aleatórios, como por exemplo: 8 x 2 = 64. Estou confusa sobre o que pode estar dando errado.

HTML:


<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css" />
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Rubik&display=swap" rel="stylesheet">
    <script src="/calculo.js" defer></script>
    <title>Calculadora</title>
</head>

<body>
    <div id="calculator">
        <div id="calc">
            <div id="last-calc"></div>
            <div id="result">
                <img src="./assets/equals.svg" alt="sinal de igual">
                <span id="resul-screen">0</span>
            </div>
        </div>

        <div id="keyboard">
            <button class="secondary" data-action="cancelEntry">CE</button>
            <button data-action="clear">C</button>
            <button data-action="%">%</button>
            <button class="tertiary" data-action="/">/</button>
            <button>7</button>
            <button>8</button>
            <button>9</button>
            <button class="tertiary" data-action="x">X</button>
            <button>4</button>
            <button>5</button>
            <button>6</button>
            <button class="tertiary" data-action="-">-</button>
            <button>1</button>
            <button>2</button>
            <button>3</button>
            <button class="tertiary" data-action="+">+</button>
            <button data-action="plusMinus"><img src="./assets/plusMinus.svg" alt="simbolo de mais sobre menos"></button>
            <button>0</button>
            <button data-action="decimal">.</button>
            <button class="quartiary" data-action="calculate">=</button>
        </div>
    </div>
</body>

</html>



JAVASCRIPT:


const calculator = document.querySelector(''#calculator'')
const keys = calculator.querySelector(''#keyboard'')
const displayPress = document.querySelector(''#last-calc'')
const display = document.querySelector(''#resul-screen'')


keys.addEventListener(''click'', e => {
    
    if (e.target.matches(''button'')) {
        const key = e.target
        const action = key.dataset.action
        const keyContent = key.textContent
        const displayedNum = displayPress.textContent

        const calculate = (n1, operator, n2) => {
            const firstNum = parseFloat(n1)
            const secondNum = parseFloat(n2)

            switch (operator) {
                case ''+'':
                    return firstNum + secondNum
                case ''-'':
                    return firstNum - secondNum
                case ''x'':
                    return firstNum * secondNum
                case ''/'':
                    return firstNum / secondNum
                case ''%'':
                    return firstNum * (secondNum / 100)
                default:
                    return null
            }
        }

        const previousKeyType = calculator.dataset.previousKeyType

        if (!action) {
            if (
                displayedNum === ''0'' || previousKeyType === ''operator'' || previousKeyType === ''calculate''
            ) {
                displayPress.textContent = keyContent
            } else {
                displayPress.textContent = displayedNum + keyContent
            }
            calculator.dataset.previousKeyType = ''number''
        }

        if (
            action === ''-'' ||
            action === ''+'' ||
            action === ''x'' ||
            action === ''/'' ||
            action === ''%'' ||
            action === ''plusMinus''
        ) {
            const firstValue = calculator.dataset.firstValue
            const operator = calculator.dataset.operator
            const secondValue = displayedNum

            if (firstValue && operator && previousKeyType !== ''operator'' && previousKeyType !== ''calculate'') {
                const calcValue = calculate(firstValue, operator, secondValue)
                display.textContent = calcValue
                calculator.dataset.firstValue = calcValue
            } else {
                calculator.dataset.firstValue = displayedNum
            }

            displayPress.textContent = displayedNum + " " + action + " "
            calculator.dataset.operator = action
        }

        if (action === ''decimal'') {
            if (!displayedNum.includes(''.'')) {
                displayPress.textContent = displayedNum + ''.''
            } else if (
                previousKeyType === ''operator'' ||
                previousKeyType === ''calculate''
            ) {
                display.textContent = ''0.''
            }
            calculator.dataset.previousKeyType = ''decimal''
        }

        if (action === ''clear'') {
            if (key.textContent === ''C'') {
                calculator.dataset.firstValue = ''''
                calculator.dataset.modValue = ''''
                calculator.dataset.operator = ''''
                calculator.dataset.previousKeyType = ''''
            } else {
                key.textContent = ''C''
            }

            display.textContent = 0
            displayPress.textContent = 0
            calculator.dataset.previousKeyType = ''clear''
        }

        if (action === ''cancelEntry'') {
            console.log(''cancel Entry!'')
        }

        if (action === ''calculate'') {
            const firstValue = calculator.dataset.firstValue
            const operator = calculator.dataset.operator
            const secondValue = displayedNum

            if (firstValue) {
                if (previousKeyType === ''calculate'') {
                    firstValue = displayedNum
                    secondValue = calculator.dataset.modValue
                }

                display.textContent = calculate(firstValue, operator, secondValue)
            }
            calculator.dataset.modValue = secondValue
            calculator.dataset.previousKeyType = ''calculate''
        }
    }
})

Andresa Ribeiro

Andresa Ribeiro

Curtidas 0

Melhor post

Frank Hosaka

Frank Hosaka

14/02/2023

Ao invés de procurar o erro, encontrei um outro programa que faz o trabalho da calculadora:
fonte: https://github.com/Nomzy-kush/CalculatorJS-Section

[code=xml]
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calculator</title>

<style>
*, *::before, *::after {box-sizing: border-box;font-family: Gotham Rounded,
sans-serif;font-weight: normal;}
body {margin: 0; padding: 0;
background: linear-gradient(to right, #CBCE91FF, #EA738DFF); }
.calculator-grid {display: grid;justify-content: center;align-content: center;
min-height: 100vh; grid-template-columns: repeat(4, 100px);
grid-template-rows: minmax(120px, auto) repeat(5, 100px);}
.calculator-grid > button {cursor: pointer;font-size: 2rem;
border: 1px, solid #FFFFFF; outline: none; }
.calculator-grid > button:hover {background-color: #a9a9a9;}
.span-two {grid-column: span 2;color: #adf802;
background-color: rgba(139, 0, 139, 0.8);}
.output{grid-column: 1 / -1;background-color: rgba(0, 0, 0, 0.75);
display: flex;align-items: flex-end;justify-content: space-around;
flex-direction: column;padding: 10px;word-wrap: break-word;
word-break: break-all;}
.output .previous-operand{color: rgba(255,255, 255, 0.75);font-size: 1.5rem;}
.output .current-operand{color: white;font-size: 2.5rem;}
</style>
</head>
<body>
<div class="calculator-grid">
<div class="output">
<div data-previous-operand class="previous-operand"></div>
<div data-current-operand class="current-operand"></div></div>
<button data-all-clear class="span-two">AC</button>
<button data-delete>DEL</button>
<button data-operation>÷</button>
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>
<button data-operation>*</button>
<button data-number>4</button>
<button data-number>5</button>
<button data-number>6</button>
<button data-operation>+</button>
<button data-number>7</button>
<button data-number>8</button>
<button data-number>9</button>
<button data-operation>-</button>
<button data-number>.</button>
<button data-number>0</button>
<button data-equals class="span-two">=</button>
</div>
</body>
<script>
class Calculator {
constructor(previousOperandTextElement, currentOperandTextElement) {
this.previousOperandTextElement = previousOperandTextElement
this.currentOperandTextElement = currentOperandTextElement
this.clear()}
clear() {
this.currentOperand = ''
this.previousOperand = ''
this.operation = undefined }
delete() {
this.currentOperand = this.currentOperand.toString().slice(0, -1)}
appendNumber(number) {
if (number === '.' && this.currentOperand.includes('.')) return
this.currentOperand = this.currentOperand.toString() + number.toString()}
chooseOperation(operation) {
if (this.currentOperand === '') return
if (this.previousOperand !== '') {
this.compute()}
this.operation = operation
this.previousOperand = this.currentOperand
this.currentOperand = ''}
compute() {
let computation
const prev = parseFloat(this.previousOperand)
const current = parseFloat(this.currentOperand)
if (isNaN(prev) || isNaN(current)) return
switch (this.operation) {
case '+':
computation = prev + current
break
case '-':
computation = prev - current
break
case '*':
computation = prev * current
break
case '÷':
computation = prev / current
break
default:
return }
this.currentOperand = computation
this.operation = undefined
this.previousOperand = '' }
getDisplayNumber(number) {
const stringNumber = number.toString()
const integerDigits = parseFloat(stringNumber.split('.')[0])
const decimalDigits = stringNumber.split('.')[1]
let integerDisplay
if (isNaN(integerDigits)) {
integerDisplay = '' } else {
integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 }) }
if (decimalDigits != null) {
return `$.$`} else {
return integerDisplay }}
updateDisplay() {
this.currentOperandTextElement.innerText =
this.getDisplayNumber(this.currentOperand)
if (this.operation != null) {
this.previousOperandTextElement.innerText =
`${this.getDisplayNumber(this.previousOperand)} ${this.operation}`
} else {
this.previousOperandTextElement.innerText = ''}}}
const numberButtons = document.querySelectorAll('[data-number]')
const operationButtons = document.querySelectorAll('[data-operation]')
const equalsButton = document.querySelector('[data-equals]')
const deleteButton = document.querySelector('[data-delete]')
const allClearButton = document.querySelector('[data-all-clear]')
const previousOperandTextElement = document.querySelector('[data-previous-operand]')
const currentOperandTextElement = document.querySelector('[data-current-operand]')
const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement)
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.appendNumber(button.innerText)
calculator.updateDisplay() }) })
operationButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.chooseOperation(button.innerText)
calculator.updateDisplay()})})
equalsButton.addEventListener('click', button => {
calculator.compute()
calculator.updateDisplay()})
allClearButton.addEventListener('click', button => {
calculator.clear()
calculator.updateDisplay()})
deleteButton.addEventListener('click', button => {
calculator.delete()
calculator.updateDisplay()})
document.addEventListener('keydown', function (event) {
let patternForNumbers = /[0-9]/g;
let patternForOperators = /[+\\-*\\/]/g
if (event.key.match(patternForNumbers)) {
event.preventDefault();
calculator.appendNumber(event.key)
calculator.updateDisplay()}
if (event.key === '.') {
event.preventDefault();
calculator.appendNumber(event.key)
calculator.updateDisplay() }
if (event.key.match(patternForOperators)) {
event.preventDefault();
calculator.chooseOperation(event.key)
calculator.updateDisplay()}
if (event.key === 'Enter' || event.key === '=') {
event.preventDefault();
calculator.compute()
calculator.updateDisplay()}
if (event.key === "Backspace") {
event.preventDefault();
calculator.delete()
calculator.updateDisplay() }
if (event.key == 'Delete') {
GOSTEI 1

Mais Respostas

Frank Hosaka

Frank Hosaka

14/02/2023

O arquivo JavaScript tem aspas demais, e eu acredito que o nome dele é calculo.js
Para testar o seu código precisávamos do endereço de onde você conseguiu os seguintes arquivos:
style.css
equals.svg
plusMinus.svg

Tirando as aspas duplas, o arquivo JavaScript (provalvelmente calculo.js) ficaria assim
const calculator = document.querySelector('#calculator')
const keys = calculator.querySelector('#keyboard')
const displayPress = document.querySelector('#last-calc')
const display = document.querySelector('#resul-screen')
 
 
keys.addEventListener('click', e => {
     
    if (e.target.matches('button')) {
        const key = e.target
        const action = key.dataset.action
        const keyContent = key.textContent
        const displayedNum = displayPress.textContent
 
        const calculate = (n1, operator, n2) => {
            const firstNum = parseFloat(n1)
            const secondNum = parseFloat(n2)
 
            switch (operator) {
                case '+':
                    return firstNum + secondNum
                case '-':
                    return firstNum - secondNum
                case 'x':
                    return firstNum * secondNum
                case '/':
                    return firstNum / secondNum
                case '%':
                    return firstNum * (secondNum / 100)
                default:
                    return null
            }
        }
 
        const previousKeyType = calculator.dataset.previousKeyType
 
        if (!action) {
            if (
                displayedNum === '0' || previousKeyType === 'operator' || previousKeyType === 'calculate'
            ) {
                displayPress.textContent = keyContent
            } else {
                displayPress.textContent = displayedNum + keyContent
            }
            calculator.dataset.previousKeyType = 'number'
        }
 
        if (
            action === '-' ||
            action === '+' ||
            action === 'x' ||
            action === '/' ||
            action === '%' ||
            action === 'plusMinus'
        ) {
            const firstValue = calculator.dataset.firstValue
            const operator = calculator.dataset.operator
            const secondValue = displayedNum
 
            if (firstValue && operator && previousKeyType !== 'operator' && previousKeyType !== 'calculate') {
                const calcValue = calculate(firstValue, operator, secondValue)
                display.textContent = calcValue
                calculator.dataset.firstValue = calcValue
            } else {
                calculator.dataset.firstValue = displayedNum
            }
 
            displayPress.textContent = displayedNum + " " + action + " "
            calculator.dataset.operator = action
        }
 
        if (action === 'decimal') {
            if (!displayedNum.includes('.')) {
                displayPress.textContent = displayedNum + '.'
            } else if (
                previousKeyType === 'operator' ||
                previousKeyType === 'calculate'
            ) {
                display.textContent = '0.'
            }
            calculator.dataset.previousKeyType = 'decimal'
        }
 
        if (action === 'clear') {
            if (key.textContent === 'C') {
                calculator.dataset.firstValue = ''
                calculator.dataset.modValue = ''
                calculator.dataset.operator = ''
                calculator.dataset.previousKeyType = ''
            } else {
                key.textContent = 'C'
            }
 
            display.textContent = 0
            displayPress.textContent = 0
            calculator.dataset.previousKeyType = 'clear'
        }
 
        if (action === 'cancelEntry') {
            console.log('cancel Entry!')
        }
 
        if (action === 'calculate') {
            const firstValue = calculator.dataset.firstValue
            const operator = calculator.dataset.operator
            const secondValue = displayedNum
 
            if (firstValue) {
                if (previousKeyType === 'calculate') {
                    firstValue = displayedNum
                    secondValue = calculator.dataset.modValue
                }
 
                display.textContent = calculate(firstValue, operator, secondValue)
            }
            calculator.dataset.modValue = secondValue
            calculator.dataset.previousKeyType = 'calculate'
        }
    }
})

Mas tem erro de lógica, e esse é mais difícil de achar.
GOSTEI 0
Andresa Ribeiro

Andresa Ribeiro

14/02/2023

Realmente o erro está na lógica, to tentando buscar qual é
GOSTEI 0
POSTAR