javascript calculator 5 + 5 = 55?

我是研究僧i 提交于 2019-12-12 15:25:28

问题


Hey I made a javascript calculator and want the to try 5 + 5 it give me 55 other then 10 ? How ever if I try 5 / 5 it give me 1 fine if i try 5 - 5 it gives me 0 fine and same with times i don't under stand the problem with my code also want to try console.log it doesn't work so I use document.write

this is my code

var Plus = function()
{
    var N1 = prompt("Enter first number");
    var N2 = prompt("Enter second number");
    var sum = (N1 + N2);
    document.write(sum);
} 

var Minus = function()
{
    var N1 = prompt("Enter first number");
    var N2 = prompt("Enter second number");
    var sum = (N1 - N2);
    document.write(sum);
}

var Division = function()
{
    var N1 = prompt("Enter first number");
    var N2 = prompt("Enter second number");
    var sum = (N1 / N2);
    document.write(sum);
}

var Times = function()
{
    var N1 = prompt("Enter first number");
    var N2 = prompt("Enter second number");
    var sum = (N1 * N2);
    document.write(sum);
}

var Answer = prompt("Plus ?, Minus ?, Division ? or Times ?");

    if( Answer === "Plus")
    {
        Plus();
    }
    else
    {
        if( Answer === "Minus")
        {
            Minus();
        }
        else
        {
            if( Answer === "Division")
            {
                Division();
            }
            else
            {
                if( Answer === "Times")
                {
                    Times();
                }
                else
                {
                    document.write("How did you get here?");
                }
            }
        }
    }

回答1:


N1 and N2 are strings, not numbers. Adding two strings together concatenates them, which is what your "error" is.

You need to parse them into numbers:

var N1 = Number(prompt("Enter first number"));



回答2:


The reason this works for other operators but not plus is because "a" + "b" = "ab".

That said, you're adding strings. So "5" + "5" = "55"

If you first convert them to integers, it should fix this.

var sum = (parseInt(N1,10) + parseInt(N2,10));



回答3:


Prompt gets you the string format of input , you need convert it into integer for integer add operation.



来源:https://stackoverflow.com/questions/17498883/javascript-calculator-5-5-55

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!