Javascript:“+"符号连接而不是给出变量的总和

Javascript: quot;+quot; sign concatenates instead of giving sum of variables(Javascript:“+符号连接而不是给出变量的总和)

本文介绍了Javascript:“+"符号连接而不是给出变量的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在创建一个网站,可以帮助我快速回答物理问题.碰巧,代码没有按预期运行,这里是代码

I am currently creating a site that will help me quickly answer physics questions. As it happens, the code didn't run as expected, here is the code

if (option == "dv") {
    var Vinitial = prompt("What is the Velocity Initial?")
    var acceleration = prompt("what is the acceleration?")
    var time = prompt("what is the time?")

    Vfinal = Vinitial + acceleration * time

    displayV.innerHTML = "v= vf= " + Vfinal + "ms" + sup1.sup();
}

现在,假设 Vinitial 是 9,加速度是 2,时间是 3.当代码运行时,Vfinal"没有得到 15,而是得到 96.我发现它可以很好地乘以加速度和时间,然后将开头的 9 与 6(2 * 3 的乘积)连接起来.

Now, let's say Vinitial was 9, acceleration was 2, and time was 3. When the code runs, instead of getting 15 for "Vfinal", I get 96. I figured out that it multiplies acceleration and time fine, and then just concatenates the 9 at the beginning, with 6 (the product of 2 * 3).

我现在已经通过使用修复它

I have fixed it for now by using

Vfinal =  acceleration * time - (-Vinitial)

避免使用+"号,但我不想继续这样做.我该如何解决?

which avoids using the "+" sign, but I don't want to have to keep doing this. How do I fix it?

推荐答案

你这里处理的是strings,对strings的数学运算会搞砸.请记住当您进行数学运算时,您必须将数据转换为实际数字,然后执行数学运算.

you are dealing with strings here, and math operations on strings will mess up. Remember when ever you are doing math operations you have to convert the data into actual numbers and then perform the math.

使用 parseInt() 更多详情这里

您的代码应更改为

Vfinal = parseInt(Vinitial,10) + parseInt(acceleration,10) * parseInt(time,10);

如果数字是十进制值,则使用parseFloat()代替

Edit 1: If the numbers are decimal values then use parseFloat() instead

所以代码是

Vfinal = parseFloat(Vinitial) + parseFloat(acceleration) * parseFloat(time);

这篇关于Javascript:“+"符号连接而不是给出变量的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Javascript:“+"符号连接而不是给出变量的总和

基础教程推荐