Unexpected output in javascript

后端 未结 5 647
旧时难觅i
旧时难觅i 2020-12-12 08:38

I am beginner to javascript and i am getting unexpected output

here is the code



        
相关标签:
5条回答
  • 2020-12-12 08:45

    prompt returns a string, not a number. + is used as both an addition and concatenation operator. Use parseInt to turn strings into numbers using a specified radix (number base), or parseFloat if they're meant to have a fractional part (parseFloat works only in decimal). E.g.:

    var num1 = parseInt(prompt("what is your no."), 10);
    //                                   radix -----^
    

    or

    var num1 = parseFloat(prompt("what is your no."));
    
    0 讨论(0)
  • 2020-12-12 08:54

    In addition to the already provided answers: If you're using parseInt() / parseFloat(), make sure to check if the input in fact was a valid integer or float:

    function promptForFloat(caption) {
        while (true) {
            var f = parseFloat(prompt(caption));
            if (isNaN(f)) {
                alert('Please insert a valid number!');
            } else {
                return f;
            }
        }
    }
    
    var num1 = promptForFloat('what is your no.');
    // ...
    
    0 讨论(0)
  • 2020-12-12 08:58

    When you prompt the user, the return value is a string, normal text.

    You should convert the strings in numbers:

    alert(add(parseInt(num1), parseInt(num2));
    
    0 讨论(0)
  • 2020-12-12 08:59

    The return value of prompt is a string. So your add function performs the + operator on 2 strings, thus concatenating them. Convert your inputs to int first to have the correct result.

        function add(a,b)
        {
            x = parseInt( a ) + parseInt( b );
            return x;
        }
    
    0 讨论(0)
  • 2020-12-12 09:01

    This is because the prompt function returns a String and not a Number. So what you're actually doing is to request 2 strings and then concatenate them. If you want to add the two numbers together you'll have to convert the strings to numbers:

    var num1 = parseFloat(prompt("what is your no."));
    var num2 = parseFloat(prompt("what is another no."));
    

    or simpler:

    var num1 = +prompt("what is your no.");
    var num2 = +prompt("what is another no.");
    
    0 讨论(0)
提交回复
热议问题