开发者

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);
    NSL开发者_运维百科og(@"(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


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜