我一直认为当浮点数被截断为整数时,它总是成为小于浮点数的最大数字。但是,当浮点数介于 -0.5 和 0 之间时,它会转换为 0 而不是 -1!为什么是这样?这是特定于语言的吗?我在 objC 中看到了这一点。
问问题
2526 次
1 回答
2
好吧,简短的回答是您的理解实际上是正确的:
0 是大于 -1 的数字。
更长或更详细的答案取决于如何将浮点数转换为整数。如果您想要“0.5”的浮点数使用“-1”而不是“0”,您可能需要编写自己的实现,将负数从浮点数中去除,将其向上或向下舍入为整数,然后相加(或相乘) 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
于 2013-03-04T03:51:30.150 回答