简体   繁体   中英

calculator using javascript code

I am trying to make a small calculator with Javascript, but the two numbers are not added or subtracted, it just gets concatenated, for example, if I want to add 2+2 it outputs " 22" not 4. , here is the code:

    <!DOCTYPE html>
    <html>
    <head>
   <title>Hello!</title>
   </head>
   <script>

  function getResult()
  {
  var result1 = document.getElementById("number1").value;
  var result3 = document.getElementById ("op1").value;

   var result2 = document.getElementById("number2").value;

    calculate (result1,result3,result2);
   }

  function calculate(num1,operator,num2)
   {

   if (operator== '+')
   {
    var res1 = num1+num2;
    alert(res1);

    }
   else if (operator== '-')
   {
    var res2 = num1-num2;
    alert(res2);

    }
    else if (operator== '*')
    {
    var res3 = num1*num2;
    alert(res3);

    }
   else if (operator== '/')
    {
    var res4 = num1/num2;
    alert(res4);
     }

   else
     {
    alert("Nothing from above!");
    }

    }
    </script>

    <body>
    <form action="get" method="#">
    <input type="text" name="text1" value="" id="number1"  />
    <input type="text" name="text2" value="" id="number2" />  <br />

  <input type="button" name="o1" value="+" id="op1" onclick="getResult();"/>
  <input type="button" name="o2" value="-" id="op2" onclick="getResult();"/>
  <input type="button" name="o3" value="*" id="op3" onclick="getResult();"/>
  <input type="button" name="o4" value="/" id="op4" onclick="getResult();"/>      

 <input type="button" name="calc" value="Calculate" onclick="getResult();"/>
 </form>

 </body>
 </html>

In JavaScript (and in many other programming languages), when you add two strings together, you get the concatenation of their values. Currently your program is treating the form inputs as strings, but you can use the built-in function parseInt to extract integers from Strings.

Try the following:

function getResult() {
    var result1 = parseInt(document.getElementById("number1").value);
    var result3 = parseInt(document.getElementById ("op1").value);
    var result2 = parseInt(document.getElementById("number2").value);

    calculate (result1,result3,result2);
}

应用parseFloat,例如

var res1 = parseFloat(num1)+parseFloat(num2);

That is because of string concatenation. Please change the code to var res1 = parseInt(num1) + parseInt(num2);

You must cast your vars to ints before doing any math with them. By default they are read in as strings. result1 = parseInt(result1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM