-->

周围使用在Javascript变量括号来改变数学计算的优先级(Using parantheses a

2019-10-29 12:23发布

我使用的是数学和变量的组合在JavaScript计算锻炼,我发现使用正确的方式括号中的困难。 例如我想要做以下计算[(4,95/ans2)-4,5]*100 ,其中ANS2是计算变量。 在最后一个字段我得到45.000和我应该采取 - 4.046 ...如果在第一场和第二场的投入是2 + 2

 <form name="Calcultor" Method="Get" id='form1'>First Number: <input type="text" name="first" size="35" id="first">+ Second Number: <input type="text" name="second" size="35" id="second"> <br>Answer: <input type="text" name="ans" size="35" id="ans" /> <input type="text" name="ans2" size="35" id="ans2" /> <input type="text" name="ans3" size="35" id="ans3" /> <button type="button" onclick="Calculate();">Calculate</button> </form> <script> function Calculate() { var first = document.getElementById('first').value; var second = document.getElementById('second').value; var ans = document.getElementById('ans').value; var ans2 = document.getElementById('ans2').value; document.getElementById('ans').value = parseInt(first) + parseInt(second); document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826; /* in the following line i can't figure how to use with a proper way parentheses to prioriterize the calculations with the way i mentioned in the example before the code snippet*/ document.getElementById('ans3').value = [( 4.95 / parseInt(document.getElementById('ans2').value)) - 4.5] * 100; } </script> 

Answer 1:

问题是此行中: document.getElementById('ans3').value = [( 4.95 / parseInt(document.getElementById('ans2').value)) - 4.5] * 100; 。 你需要使用()代替[]为分组,你也不必parseInt值。 这里是工作的代码片段:

 function Calculate() { var first = document.getElementById('first').value; var second = document.getElementById('second').value; var ans = document.getElementById('ans').value; var ans2 = document.getElementById('ans2').value; document.getElementById('ans').value = parseInt(first) + parseInt(second); document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826; /* in the following line i can't figure how to use with a proper way parentheses to prioriterize the calculations with the way i mentioned in the example before the code snippet*/ document.getElementById('ans3').value = ((4.95 / document.getElementById('ans2').value) - 4.5) * 100 } 
 <form name="Calcultor" Method="Get" id='form1'>First Number: <input type="text" name="first" size="35" id="first">+ Second Number: <input type="text" name="second" size="35" id="second"> <br>Answer: <input type="text" name="ans" size="35" id="ans" /> <input type="text" name="ans2" size="35" id="ans2" /> <input type="text" name="ans3" size="35" id="ans3" /> <button type="button" onclick="Calculate();">Calculate</button> </form> 



文章来源: Using parantheses around variables in Javascript to change priority in math calculations