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

时间:2021-02-18 07:21:45

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.

简单的问题,我知道必须有一个正确的方法来做到这一点。我有一个CGFloat,增量为1/16。我想确定这个值何时变成一个整数。

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的想法。

3 个解决方案

#1


4  

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/16是2 ^( - 4)并且此数字可以精确地用float表示:

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

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

    NSLog(@"OK!");
}

#2


2  

It's better to do it the other way around, i.e. 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...
    }
}

#3


1  

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."

“由于缺乏正确的方法,我想出的想法就像有另一个变量来跟踪迭代次数和mod 16。”

This is a wonderful idea.

这是一个很棒的主意。

#1


4  

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/16是2 ^( - 4)并且此数字可以精确地用float表示:

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

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

    NSLog(@"OK!");
}

#2


2  

It's better to do it the other way around, i.e. 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...
    }
}

#3


1  

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."

“由于缺乏正确的方法,我想出的想法就像有另一个变量来跟踪迭代次数和mod 16。”

This is a wonderful idea.

这是一个很棒的主意。