JavaScript - cannot add 2 numbers correctly

爱⌒轻易说出口 提交于 2020-01-05 08:30:26

问题


I am simulating a calculator using Javascript.

Where a user can input 2 numbers in a given text box, and it will display sum, product, difference and division.

Here is my function-

function calculate(num1, num2) {
  console.log("First Number = " + num1 + " Second Number = " + num2);
  console.log("Sum = " + (num1 + num2));
  console.log("Product =" + (num1 * num2));
  console.log("Difference = " + (num1 - num2));
  console.log("Division = " + (num1 / num2));
}

When user inputs 1st number 4 and second number 3 i get this result:

First Number = 4 Second Number = 3
Sum = 43  // sum should be 7 NOT 43
Product = 12 
Difference = 1 
Division = 1.3333333333333333 

Any ideas what is wrong here?


回答1:


Because + is also a String Concatinater in JavaScript. use parseInt(var1) + parseInt(var2) it will work. also have a look on ---> Javascript Operators

to understand the + operator. Thanks




回答2:


If you're taking in the numbers in a text box they're treated as strings, so the + operator will do string concatenation. The * operator doesn't mean anything in relation to strings, so the javascript engine will try to interpret the inputs as numbers.

You can use parseInt on the inputs to convert them to numbers, or use the html number input type.




回答3:


try

console.log("Sum = " + (parseInt(num1) + parseInt(num2)));

or

console.log("Sum = " + (0 + num1 + num2));

also make sure you are calling the function like

calculate(4, 3);

and not

calculate('4', '3');



回答4:


At least one of your inputs to calculate() is string. + is defined for string so become 43. While */- are not defined for string and Javascript "cleverly" convert them to int.



来源:https://stackoverflow.com/questions/26308704/javascript-cannot-add-2-numbers-correctly

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