How to make a simple calculator with pure Javascript?

Asked

Viewed 2,171 times

-1

Good staff I am beginner in the area of web and Javascript. My teacher asked me to prepare a simple Calculator with the four operations (+), (-), (*), (/). Only with pure Javascript to run on the terminal, no HTML code or other. Then I saw that there is a need to create the questions about which operation the user wants to perform, as well as enter the first and the second number. I used IF/Else, I was able to run the code, but when showing the result it returns Nan. Could someone help? That is the code:

var valor
var valor1
var oper
var readlineSync = require('readline-sync');
oper = parseFloat(readlineSync.question("Qual operacao deseja efetuar (+) (-) (*) (/)? : \n"));
valor = parseFloat(readlineSync.question("Insira o primeiro numero: \n"));
valor1 = parseFloat(readlineSync.question("Insira o segundo numero: \n"));
   if (oper =="+") {
      return valor + valor1;
} else if 
      (oper == "-") {
      return valor - valor1;
   } else if
       (oper == "*") {
         return valor * valor1;
      } else if 
         (oper == "/") {
        return valor / valor1;
      } else {
      console.log('Não foi possível calcular')
      }
      console.log('O resultado é', +oper) 
  • 1

    Ronde, you are wearing parseFloat to receive the value in oper.

2 answers

1


In your code there are a few things to adjust. First you are passing a float to the variable oper and another point is that you are using Return, but you are not in within a function.

I made an example using function so you can use a good part of your code and make only a few adjustments.

I hope it helps.

var valor
var valor1
var oper
var readlineSync = require('readline-sync');
oper = readlineSync.question("Qual operacao deseja efetuar (+) (-) (*) (/)? : \n");
valor = parseFloat(readlineSync.question("Insira o primeiro numero: \n"));
valor1 = parseFloat(readlineSync.question("Insira o segundo numero: \n"));

function doOperation(operator, value1, value2) {
    if (operator == "+") {
        return value1 + value2;
    } else if
        (operator == "-") {
        return value1 - value2;
    } else if
        (operator == "*") {
        return value1 * value2;
    } else if
        (operator == "/") {
        return value1 / value2;
    } else {
        throw new Error('Operação inválida');
    }
}


console.log('O resultado é', doOperation(oper, valor, valor1)) 

I placed the verification code inside a function. It always returns the value according to the operation, if the operation is not specified, it launches an Error.

  • Thanks, friend helped me so much. This is exactly what I needed to do!

-2

Cleanse 7 8 9 / 6 5 4 X 3 2 1 -
  </div>
  <div class="row pb-2">
     <div class="col-md-3">
        <button type='button' class='btn btn-outline-secondary btn-lg btn-block'>0</button>
     </div>
     <div class="col-md-3">
        <button type='button' class='btn btn-outline-secondary btn-lg btn-block'>,</button>
     </div>
     <div class="col-md-3">
        <button type='button' class='btn btn-outline-secondary btn-lg btn-block'>=</button>
     </div>
     <div class="col-md-3">
        <button type='button' class='btn btn-outline-secondary btn-lg btn-block'>+</button>
     </div>
  </div>
$(Document). ready(Function(){ var valor1 = 0; var valor2 = 0; var Oper = '; var result = 0; $('button'). click(Function(){ $this = $(this); $('#result'). val($('#result').val()+$this.html()); if(checkchar(checklast($('#result').val()) === 'Operator'){ value1 = $('#result'). val(). split(checklast($('#result').val())[0]; Oper = checklast($('#result').val()); $('#result'). val('); } if(checkchar(checklast($('#result').val()) === 'Equal'){ value2 = $('#result'). val()/*. split(Oper)[1];*/ switch(Oper){ case 'X': result = parseFloat(value1)*parseFloat(value2);break; case '/': result = parseFloat(value1)/parseFloat(value2);break; case '+': result = parseFloat(value1)+parseFloat(value2);break; case '-': result = parseFloat(value1)-parseFloat(value2);break; } $('#result'). val(result) } }) }) Function checklast(value){ Return value.substr(value.length-1,value.length); } Function checkchar(Character){ var number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; var Operator = ['X', '/', '-', '+']; // Checks if it is a number for(i in number){ if(Character.length>1){ // each Character character for(l in Character.length){ if(Character[l] === number[i]){ Return 'number' } } }Else{ if(Character === number[i]){ Return 'number' } } } // Checks if you are an operator for(o in Operator){ if(Character === Operator[o]){ Return 'Operator' } } // verifying whether it is the sign of equal if(Character === '='){ Equal Return; } // Check if it is the comma (separator) if(Character === ','){ Return '.'; } }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.