Strange math in Objective C

I am getting an unexpected value with a simple math calculation in Objective C. I have outputted three different parts of the calculation, as well as the result of the calculation below.

The following code

    NSLog(@"self.contentView.bounds.size.width: %f", self.contentView.bounds.size.width);
    NSLog(@"SWATCHES_WIDTH: %f", SWATCHES_WIDTH);
    NSLog(@"RIGHT_MARGIN: %f", RIGHT_MARGIN);
    NSLog(@"(self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN): %f", (self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN));

      

gives the following output:

self.contentView.bounds.size.width: 288.000000
SWATCHES_WIDTH: 82.000000
RIGHT_MARGIN: 12.000000
(self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN): 214.000000

I expect the result to be 194 instead of 214 (288-82-12 = 194). Can anyone please give some insight into why this is calculated the way it is and what can I do to fix it? Thank!

As far as I know, all three of these values ​​are CGFloats. The two constants are defined as follows:

#define SWATCHES_WIDTH      SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0
#define RIGHT_MARGIN        12.0

      

+2


source to share


2 answers


It:

self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN

      

applies to this:

self.contentView.bounds.size.width - SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0 - RIGHT_MARGIN

      



What do you really want:

self.contentView.bounds.size.width - SWATCH_SIZE * 3.0 - SPACE_BETWEEN * 2.0 - RIGHT_MARGIN
self.contentView.bounds.size.width - (SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0) - RIGHT_MARGIN

      

You need to add parentheses around it for it to expand correctly:

#define SWATCHES_WIDTH  (SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0)

      

+7


source


Block CPP Again!

Your subtraction after running cpp comes from this:

(self.contentView.bounds.size.width - SWATCHES_WIDTH - RIGHT_MARGIN)

:

(self.contentView.bounds.size.width - SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0 - 12.0)



See the problem?

You want SWATCHES_WIDTH to expand with parsers around it so you get what you expect

(self.contentView.bounds.size.width - (SWATCH_SIZE * 3.0 + SPACE_BETWEEN * 2.0) - 12.0)

So, you are subtracting, not adding SPACE_BETWEEN*2.0

to your result.

+1


source







All Articles