Objective-C浮点舍入

CodeGuy

如何将浮点数舍入到Objective-C中最接近的整数:

例:

float f = 45.698f;
int rounded = _______;
NSLog(@"the rounded float is %i",rounded);

应打印“四舍五入为46”

戴夫

推荐的方法是在此答案中:https : //stackoverflow.com/a/4702539/308315


原始答案:

加0.5后将其转换为int。

所以

NSLog (@"the rounded float is %i", (int) (f + 0.5));

编辑:您要求的方式:

int rounded = (f + 0.5);


NSLog (@"the rounded float is %i", rounded);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章