Objective-C浮点四舍五入 [英] Objective-C Float Rounding
本文介绍了Objective-C浮点四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
float f = 45.698f;
int rounded = _______;
NSLog(@四舍五入的浮点数是%i,舍入);
应该打印出四舍五入的浮点数为46
解决方案
推荐的方法是在这个答案: https://stackoverflow.com/a / 4702539/308315
原始答案:
<添加0.5后将其转换为int。
所以
NSLog(@四舍五入的浮点数是%i,(int)(f + 0.5));
编辑:您要求的方式:
int rounded =(f + 0.5);
NSLog(@四舍五入的浮点数是%i,四舍五入);
How might I round a float to the nearest integer in Objective-C:
Example:
float f = 45.698f;
int rounded = _______;
NSLog(@"the rounded float is %i",rounded);
should print "the rounded float is 46"
解决方案
The recommended way is in this answer: https://stackoverflow.com/a/4702539/308315
Original answer:
cast it to an int after adding 0.5.
So
NSLog (@"the rounded float is %i", (int) (f + 0.5));
Edit: the way you asked for:
int rounded = (f + 0.5);
NSLog (@"the rounded float is %i", rounded);
这篇关于Objective-C浮点四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文