2015-07-06 31 views
-3

http://unkk9a8915e1.neonz27.koding.io/genetics的Javascript添加整数作为一个字符串

例如,如果你加6和4的1-2范围内你会得到641或642,而不是11或12!

function calculate() 
 
{ 
 
    var radius1 = document.getElementById("cell1Value").value; 
 
    var radius2 = document.getElementById("cell2Value").value; 
 
    var radiusAvrg = (radius1 + radius2)/2; 
 
    var childRadius = radius1 + radius2 + (Math.floor(Math.random() * 6) + 1); 
 
    console.log(childRadius); 
 
    confirm("The child's radius is " + childRadius); 
 
}
<h1>ParentCell01's Radius</h1> 
 
<input type="text" name="cell1Value" id="cell1Value" /> 
 
<br /> 
 
<h1>ParentCell02's Radius</h1> 
 
<input type="text" name="cell2Value" id="cell2Value"/> 
 
<br /> 
 
<button onclick="calculate()">Calculate child's radius.</button>

+0

你忘了提问了。 – nnnnnn

回答

2

您需要的值转换为数字:

var radius1 = +document.getElementById("cell1Value").value; 
var radius2 = +document.getElementById("cell2Value").value; 
+0

非常感谢! :D – Neonz27

0

你需要做数学运算一样

var radius1 = parseInt(document.getElementById("cell1Value").value); 
+0

试过它没有工作! – Neonz27

+1

为什么你用parseInt代替铸造? – Qwertiy

+0

@josephcoggins,因为你需要投这两个值。 – Qwertiy

0
前解析包含int值的字符串

这里你的功能应该看起来像。

function calculate() 
     { 
      var radius1 = parseInt(document.getElementById("cell1Value").value); 
      var radius2 = parseInt(document.getElementById("cell2Value").value); 
      var radiusAvrg = (radius1 + radius2)/2; 
      var childRadius = radius1 + radius2 + (Math.floor(Math.random() * radiusAvrg) + 1); 
      console.log(childRadius); 
      confirm("The child's radius is " + childRadius); 
     } 
相关问题