skip to Main Content

This code is supposed to calculate the sum, substract, multiply, divide at the same time when the user types in x and y but it’s showing Nan

function perform(x, y) {
  x = prompt("enter first no. ")
  y = prompt(" enter second no. ")

  function sum(x, y) {
    console.log(parseInt(x + y));
  }

  sum();

  function minus(x, y) {
    console.log(parseInt(x - y));
  }

  minus();

  function multiply(x, y) {
    console.log(parseInt(x * y));
  }

  multiply();
  
  function divide(x, y) {
    console.log(parseInt(x / y));
  }

  divide();
}

2

Answers


  1. Both X and Y are strings, when entered via the prompt dialog. You need to parse them separately before adding them, e.g.:

    function sum(x, y) {
        console.log(parseInt(x) + parseInt(y));
    }
    

    In addition, you are calling all the methods without providing the variable inputs, so instead of sum(), you should call sum(x,y)

    Login or Signup to reply.
  2. prompt will return A string containing the text entered by the user, or null. as stated in the mdn docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt

    So instead of parseInt(x - y) you should first parse each input into a integer (or float) and then do the addition, multiplication etc.

    (function perform() {
      const x = parseInt(prompt("enter first no. "))
      const y = parseInt(prompt("enter second no. "))
    
      sum(x, y);
      minus(x, y);
      multiply(x, y);
      divide(x, y);
    })();
    
    function sum(x, y) {
      console.log(x + y);
    }
    
    function minus(x, y) {
      console.log(x - y);
    }
    
    function divide(x, y) {
      console.log(x / y);
    }
    
    function multiply(x, y) {
      console.log(x * y);
    }

    and please read the so link commented by @Ivar

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search