Jquery/Javascript Math: Why are these two 1 line math problems not giving the same answer?
Shouldn't these two math problems give the same answer? Brackets/parenthesis are done first, right? so it should add them all, then divide it by 2, then subtract 10. The second answer below is the one giving me the correct value that I need, the other one gives a value that's a long ways off.
var pleft = $(this).offset().left + ($(this).width() /2) - ($("#question-wrapper").width() / 2) - 10;
var pleft = (($(this).offset().left + $(this).wid开发者_如何学Goth() + $("#question-wrapper").width()) / 2) - 10;
var x = $(this).offset().left;
var y = $(this).width();
var z = $("#question-wrapper");
var pleft = x + (y/2) - (z/2) - 10
var pleft = ((x + y + z) / 2) - 10
Hopefully that helps clear up the difference.
I've decomposed the formulas so you can see:
var pleft = $(this).offset().left <------------------- not divided
+ ($(this).width() /2)
- ($("#question-wrapper").width() / 2)
- 10;
var pleft = (
(
$(this).offset().left <--------------------- divided
+ $(this).width()
+ $("#question-wrapper").width()
)
/ 2)
- 10;
In the first case, $(this).offset().left is not divided by 2 whereas in the second case it is, that's why they don't give the same result
In the first you never divide the first part with 2. That's why it's off.
var pleft = ($(this).offset().left / 2) + ($(this).width() /2) - ($("#question-wrapper").width() / 2) - 10;
Brackets/parenthesis are done first, right?
Yes, but they're not completely equivalent in your examples.
What your code did:
- a + b/2 - c/2, then subtract 10
- (a + b - c) / 2, then subtract 10
精彩评论