如何将浮点数舍入到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);
使用C标准函数族round()
。roundf()
为float
,round()
为double
和roundl()
为long double
。然后,您可以将结果转换为您选择的整数类型。
对于四舍五入float
到最接近的整数使用roundf()
roundf(3.2) // 3
roundf(3.6) // 4
您也可以使用ceil()
函数始终从中获取较高的值float
。
ceil(3.2) // 4
ceil(3.6) // 4
为了最低的价值 floor()
floorf(3.2) //3
floorf(3.6) //3
在objective-c中对浮点取整的最简单方法是lroundf
:
float yourFloat = 3.14;
int roundedFloat = lroundf(yourFloat);
NSLog(@"%d",roundedFloat);
检查手册页中的 rint()
如果要以整数舍入以下浮点值,则是在目标C中舍入浮点值的简单方法。
int roundedValue = roundf(Your float value);
让我们尝试一下并结帐
//Your Number to Round (can be predefined or whatever you need it to be)
float numberToRound = 1.12345;
float min = ([ [[NSString alloc]initWithFormat:@"%.0f",numberToRound] floatValue]);
float max = min + 1;
float maxdif = max - numberToRound;
if (maxdif > .5) {
numberToRound = min;
}else{
numberToRound = max;
}
//numberToRound will now equal it's closest whole number (in this case, it's 1)
本文地址:http://ios.askforanswer.com/objective-cfudiansheru.html
文章标签:floating-point , ios , iphone , objective-c , rounding
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
文章标签:floating-point , ios , iphone , objective-c , rounding
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!