r0b33 r0b33 - 7 months ago 24
Javascript Question

Javascript loop calculation






var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;

while (lvl < 5) {
document.ofrm.UpgSD.value += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
lvl++;
}

<form name="ofrm">
<input type="text" name="UpgSD" size="50" tabindex="1">
</form>





The result is 363147633676050952513778, instead of 363+1476+3367+6050+9525+13778 = 34559. How can I fix this?

Answer

Here's an updated code. 1. Your loop condition needs to be corrected. 2. .value is string. You can set to a variable and then attach it.

var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;
var number = 0;


while (lvl <= 5) {
  number += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
  lvl++;
}
 document.ofrm.UpgSD.value = number;
<form name="ofrm">
  <input type="text" name="UpgSD" size="50" tabindex="1">
</form>