Javascript simple math error
I can't understand whats causing this, although math has never been my specialty so any help is appreciated. My simple equation is in two parts:
Answer 1) 226 - [value] multiplied by .9
Answer 2) 226 - [value] multipli开发者_运维知识库ed by .55
If you use 40 as the input value, my calculator says:
Answer 1) 226 - 40 = 186 * .9 = 167.4
Answer 2) 226 - 40 = 186 * .55 = 102.3
But my code says:
Answer 1) 190
Answer 2) 204
My Code:
HTML:
<input id="HR"size="4" value="" /><span id="number"></span>
Answer 1 <strong><span id="answer1"></span></strong><br>
Answer 2 <strong><span id="answer2"></span></strong>
</p>
<a href="#" class='THR'>click to calculate</a>
Script:
<script type="text/javascript">
$('a.THR').click(function() {
var value = parseInt( $( "#HR" ).val() );
$( "#answer1" ).html( 226 - value * 0.9 );
$( "#answer2" ).html( 226 - value * 0.55 );
return false;
});
</script>
You are forgetting order of operations. Multiplication has higher precedence than addition/subtraction. Put parenthesis around your 226-value
$( "#answer1" ).html( (226 - value) * 0.9 );
$( "#answer2" ).html( (226 - value) * 0.55 );
Rereading your question, I'm not sure what exactly your desired result is. If you want to do the multiplication first and then the subtraction, you don't need the parenthesis, though it may be helpful to write 226 - (value * 0.9)
to make it clear. What is happening on your calculator though is that you are typing 226 - value
and then multiplying that result by your decimal number. So the above code, (226 - value) * 0.9
, represents your typing. It may help to describe what you are trying to do from the end user's perspective to decide where your parentheses go.
Parentheses: you need them.
$( "#answer1" ).html( (226 - value) * 0.9 );
$( "#answer2" ).html( (226 - value) * 0.55 );
Multiplication takes precedence over substraction.
Hence the expressions will be interpreted as:
Answer 1) 226 - ([value] multiplied by .9 )
e.g:
226 - (40 *0.9) = 226 - 36 = 190
Answer 2) 226 - ([value] multiplied by .55)
e.g:
226 - (40 * .55) = 226 - 22 = 204
You're code is honoring the standard order of operations:
- Parentheses,
- Exponeniation,
- Multiplcation/Division
- Addition/Subtraction
...but you are not. Parenthesize your equation to change the order to what you want.
This is just an order-of-operations issue (nothing to do with jquery). Multiplication/division is performed before addition/subtraction. So:
226 - 40*.9 = 226 - 36 = 190
In math, multiplication takes precedence over addition and subtraction. Use parentheses to clarify:
$( "#answer1" ).html( (226 - value) * 0.9 );
$( "#answer2" ).html( (226 - value) * 0.55 );
精彩评论