简单的JavaScript功能 - 数学加法/不工作?
问题描述:
这是我的功能:
var ans=(X*X)/(Y+Z);
当我输入 10
, 20
和 10
- 款分别增加一点出来为 2010
,而不是 30
。
我该如何解决这个问题?
When I enter 10
, 20
, and 10
- respectively- the addition bit comes out as 2010
and not 30
.
How can I fix this?
答
请确保您的字符串转换为数字第一:
Make sure to convert your strings to numbers first:
var X = "10";
var Y = "20";
var Z = "10";
X = +X; // unary plus operator converts to a number
Y = Number(Y); // or use the Number function
Z = parseInt(Z, 10); // or parseInt
var ans=(X*X)/(Y+Z);