Search code examples
javascriptnumbersprompt

adding numbers in positive and negative numbers in a javascript prompt


I'm trying to write a script on a webpage that presents the user with an arithmetic problem (EG what is 2 + -4) and asks for the answer using a prompt. then give them the feedback using an alert box. the integers have to be between -10 and 10 so far I've tried this and no luck:

var num = Math.Floor((Math.random() * -10) + 10);
var numPrompt = prompt("what is " + (num + num));
alert(numPrompt);

then I tried:

var num = Math.Floor((Math.random() * -10) + 10);
var numPrompt = prompt( "what is " + (parseInt(num) + parseInt(num)) );
alert(numPrompt); 

both failed, but why?


Solution

  • Here's something similar to what you want:

    var num1 = Math.floor((Math.random() * -21) + 11);
    var num2 = Math.floor((Math.random() * -21) + 11);
    var userAnswer = prompt('What is ' + num1 + ' + ' + num2 + '?');
    if (userAnswer.trim() !== '' && +userAnswer === num1 + num2) {
        alert('Correct');
    } else {
        alert('Wrong');
    }
    

    Since num1 and num2 are numbers being generated by the Javascript, we can simply compare the number +userAnswer to num1 + num2.

    The reason for doing +userAnswer is the userAnswer variable contains the answer returned by the prompt function, which is a string, so putting a + sign infront of it converts it to a number.

    I like +userAnswer more than parseInt because parseInt('5a') returns 5 where as +'5a' returns 0.

    The only we have to watchout for is +'' or +' ' returns 0 so we have to do an additional check to make sure the user didn't just press enter without typing a number.