简体   繁体   中英

objective-c check equality of float and int — does 2.0000 == 2

Simple question, I know there must be a correct way to do this. I have a CGFloat that increases in increments of 1/16. I want to determine when this value becomes a whole number.

For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations and mod 16 it.

While you generally can't count on fractional floating point numbers to sum up to whole numbers, your case is exception to the rule since 1/16 is 2^(-4) and this number can be represented by float precisely:

- (void)testFloat
{
    float a = 0.0f;

    while (a != 2.0f) {
        a += 0.0625f;
    }

    NSLog(@"OK!");
}

It's better to do it the other way around, ie use an integer loop counter and convert this to a float:

for (int i = 0; i < 100; ++i)
{
    float x = (float)i / 16.0f;

    if (i % 16 == 0)
    {
        // if x is whole number...
    }
}

Floating point arithmetic is inexact so you can't count on the value of your variable ever being exactly 2.0000 .

"For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations andmod 16 it."

This is a wonderful idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM