NSNumber 和 intValue:奇怪的行为
我是 Obj-C 的菜鸟,但今天我遇到了一些我自己无法理解的 NSNumber 和 intValue 事情。
我有这个示例代码:
double quota = 203/100.0;
NSLog(@"%f %f %@ %d",
quota,
quota*100.0,
[NSNumber numberWithDouble:(quota*100.0)],
[ [NSNumber numberWithDouble:(quota*100.0)] intValue]
);
它打印输出:
2.030000 203.000000 203 202
请有人帮助我理解为什么最终的 intValue 将 203 变成 202? 我觉得我错过了一些非常明显和重要的东西。
TIA
I'm a noob with Obj-C, but today I'm experiencing something I really can't understand on my own with NSNumber and intValue.
I have this example code:
double quota = 203/100.0;
NSLog(@"%f %f %@ %d",
quota,
quota*100.0,
[NSNumber numberWithDouble:(quota*100.0)],
[ [NSNumber numberWithDouble:(quota*100.0)] intValue]
);
which prints the output:
2.030000 203.000000 203 202
Please can someone help me to understand why the final intValue turns the 203 in 202?
I feel like I'm missing something really obvious and important.
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我运行了你的代码,结果 203/100.0 = 2.0299999999999998 同时存储为双精度。看起来 NSNumber 以及 %f 在打印时将其舍入为 2.03,但是当您获得 202.99999999999998 的 int 值时,.99999999999998 将被删除。希望有人(或我自己进行编辑)可以补充为什么在打印双精度值时会发生这种舍入行为。
I ran your code and the result of 203/100.0 = 2.0299999999999998 while stored as a double. It looks like
NSNumber
as well as %f is rounding it to 2.03 when printing it but when you get the int value for 202.99999999999998 the .99999999999998 is being dropped. Hopefully someone (or my self with an edit) can add to why this rounding behavior is occurring when printing the double value.