简体   繁体   English

objective-c检查float和int的相等性-2.0000 == 2

[英]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. 我有一个CGFloat,它以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. 由于缺乏正确的方法,我想出了一些想法,例如拥有另一个变量来跟踪迭代次数并对其进行mod 16处理。

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: 虽然通常不能依靠小数浮点数求和来求和,但是由于1/162^(-4) ,因此您的情况是该规则的例外,并且该数字可以精确地用float表示:

- (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 . 浮点算术是不精确的,因此您不能指望变量的值正好是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." “由于缺乏正确的方法,我想出了一些想法,例如拥有另一个变量来跟踪迭代次数并将其设为16。”

This is a wonderful idea. 这是一个很棒的主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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