JS中的计算器

时间:2019-05-25 17:53:25

标签: javascript function variables calculator

我试图用JS制作一个非常简单和基本的计算器。对于计算器的“加法”部分,输入的数字将无法正确添加... 例如: 12 + 12表示为“ 1212”而不是24 要么 6 + 15表示为“ 615”而不是21 谁能告诉我为什么?

<!DOCTYPE html>
<html>
<head>
<button onclick="Divide()">Divide</button> </br>
<button onclick="Multiply()">Multiply</button> </br>
<button onclick="Add()">Add</button> </br> 
<button onclick="Subtract()">Subtract</button> </br>
    <script>
    function Divide (){
        var dividend = prompt("What is the dividend?")
        var divisor = prompt("What is the divisor")
        var answer = prompt(dividend / divisor)
    }
    function Multiply (){
        var Number1 = prompt("What is the first number")
        var Number2 = prompt("What is the second number")
        var answer = prompt(Number1 * Number2)
    }
        function Subtract (){
        var Number1 = prompt("What is the first number")
        var Number2 = prompt("What is the second number")
        var answer = prompt(Number1 - Number2)
    }
    function Add (){
        var Number1 = prompt("What is the first number")
        var Number2 = prompt("What is the second number")
        var answer = prompt(Number1 + Number2) 
    }

</script>


</head>
<body>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

JavaScript正在将用户输入作为字符串数据。 +符号将字符串连接起来。另外,您想使用parseInt()将字符串数据转换为整数:

var answer = prompt(parseInt(Number1) + parseInt(Number2));