当将float转换为int时,为什么数字> -1和< -0.5转到-1,数字> = -0.5和< 0转到0?

时间:2013-03-04 03:48:25

标签: objective-c casting floating-point truncate floating-accuracy

我一直认为当浮点数被截断为整数时,它总是变成小于浮点数的最大数字。但是,当float在-0.5和0之间时,它将转换为0而不是-1!为什么是这样?这种语言特定吗?我在objC中看到了这一点。

1 个答案:

答案 0 :(得分:2)

嗯,简短的回答是你的理解实际上是正确的:

0是一个大于-1的数字。

更长或更详细的答案取决于浮点数如何转换为整数。如果你希望“-1”而不是“0”表示浮点数为“0.5”,你可能需要编写自己的实现来剥离浮动的负数,将其向上或向下舍入为整数,然后添加(或乘以a -1,确切地说是负号。回到它上面。

以下是我编写的一些代码,用于演示实现中的差异:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // insert code here...
        NSLog(@"Hello, World!");
        float floatNumber = -1.0f;
        for(NSInteger index = 0; index < 20; index++)
        {
            NSLog( @"floatNumber is %4.2f and integer is %d %d", floatNumber, (int) floatNumber, (int)roundf(floatNumber));
            floatNumber+=0.1f;
        }
    }
    return 0;
}

在Xcode下,结果如下:

floatNumber is -1.00 and integer is -1 -1
floatNumber is -0.90 and integer is 0 -1
floatNumber is -0.80 and integer is 0 -1
floatNumber is -0.70 and integer is 0 -1
floatNumber is -0.60 and integer is 0 -1
floatNumber is -0.50 and integer is 0 0
floatNumber is -0.40 and integer is 0 0
floatNumber is -0.30 and integer is 0 0
floatNumber is -0.20 and integer is 0 0
floatNumber is -0.10 and integer is 0 0
floatNumber is 0.00 and integer is 0 0
floatNumber is 0.10 and integer is 0 0
floatNumber is 0.20 and integer is 0 0
floatNumber is 0.30 and integer is 0 0
floatNumber is 0.40 and integer is 0 0
floatNumber is 0.50 and integer is 0 1
floatNumber is 0.60 and integer is 0 1
floatNumber is 0.70 and integer is 0 1
floatNumber is 0.80 and integer is 0 1
floatNumber is 0.90 and integer is 0 1