Richard
Richard

Reputation: 23

Weird math in Objective C

I am getting an unexpected value with a simple math calculation in Objective C. I have output the 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 would expect the result would be 194 instead of 214 (288-82-12=194). Can anyone give any insight as to why this is being calculated the way it is and what I can do to fix it? Thanks!

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

Upvotes: 2

Views: 302

Answers (2)

John Kugelman
John Kugelman

Reputation: 361595

This:

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

is expanding to this:

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

What you really want is:

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 so it is expanded properly:

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

Upvotes: 7

Jack Lloyd
Jack Lloyd

Reputation: 8405

CPP strike again!

Your subtraction, after cpp runs, goes from this:

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

to this:

(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 parens around it, so that you get what you expect, which is

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

So you're subtracting rather than adding SPACE_BETWEEN*2.0 to your result.

Upvotes: 1

Related Questions