views:

58

answers:

3

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).width() + $("#question-wrapper").width()) / 2) - 10;
A: 

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:

  1. a + b/2 - c/2, then subtract 10
  2. (a + b - c) / 2, then subtract 10
jensgram
+5  A: 
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.

EMMERICH
+1  A: 

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

wildpeaks