在Objective-C中,如何将浮点舍入为最接近的整数:
例子:
float f = 45.698f;
int rounded = _______;
NSLog(@"the rounded float is %i",rounded);
应打印"四舍五入浮动为46"
在Objective-C中,如何将浮点舍入为最接近的整数:
例子:
float f = 45.698f;
int rounded = _______;
NSLog(@"the rounded float is %i",rounded);
应打印"四舍五入浮动为46"
建议的答案是:https://stackoverflow.com/a/4702539/308315
原始答案:
添加0.5后将其转换为整数.
所以
NSLog (@"the rounded float is %i", (int) (f + 0.5));
编辑:你要求的方式:
int rounded = (f + 0.5);
NSLog (@"the rounded float is %i", rounded);