<script type="text/javascript"> function myfunc() { var first = document.getElementById('first').value; var second = document.getElementById('second').value; alert((first+second)/2); } </script> </html>
the results usually end up either correct or extremely off, like sometimes when I try to calculate the midpoint of 1 and 10 it shows up as 55
结果通常要么是正确的,要么是非常不正确的,就像有时我试图计算1和10的中点时,结果显示为55
更多回答
Have you tried parsing your input as a number with parseInt() or something similiar? If there are any extra spaces or if the input is not properly read as an actual number, your results will be incorrect.
The value property is a string, so + performs string concatenation rather than numeric addition. Instead, you could use inputs with type set to "number" and read the valueAsNumber property.
.value returns results as text. So when you enter 1 for the first input field and 10 for the second input field, and then use +, you are doing string concatenation ("1" + "10" = 110) rather than numeric addition. You may find the parseInt method to be of help.
As a broader note, you have both of those input fields specified as text, which means I could enter "one" and "ten" and that would be accepted, but throw an error when doing mathematics. You might want to consider if there's another input type that would restrict entry to numbers or explicitly handle that case in your code.
Try to parse each input first as an integer. This can help you avoid the issue where the result is incorrectly calculated if the "number" provided in the <input> is actually a string instead.
<script type="text/javascript"> function myfunc() {
//Parse the value, which may be a string, as an integer. If the input is not a valid integer, an error will be thrown accordingly var first = parseInt(document.getElementById('first').value); var second = parseInt(document.getElementById('second').value); alert((first+second)/2); } </script> </html>
On a further note, using parseInt() will parse numbers with decimals as integers. You may need to take this into account when doing your calculations where the input values may be a float.
<script type="text/javascript"> function myfunc() { var first_as_string = document.getElementById('first').value; var second_as_string = document.getElementById('second').value; const first = parseInt(first_as_string); const second = parseInt(second_as_string); alert((first+second)/2); } </script> </html>```
The problem with your current is that "first" and "second" variables are retrieved as string so the Javascript engine will do a concatenation then convert it to number and make division operation.
<script type="text/javascript"> function myfunc() { var first = document.getElementById('first').value; var second = document.getElementById('second').value; alert((Number(first)+Number(second))/2); } </script>
我是一名优秀的程序员,十分优秀!