Ios 将浮点舍入到.5处的下一个整数
我以为Ios 将浮点舍入到.5处的下一个整数,ios,objective-c,floating-point,rounding,Ios,Objective C,Floating Point,Rounding,我以为lrundf会将我的浮点值四舍五入到0.5步的下一个最高值。例如,1.5f将四舍五入为2.0f 我试过了,但代码告诉我不是这样: int roundUp = 1.5f; NSLog(@"no round up: %d", roundUp); NSLog(@"lroundf: %ld", lroundf(roundUp)); 我的输出是: no round up: 1 lroundf: 1 如何正确地对浮点进行取整?首先使用float(或double)而不是int…*facepalm*
lrundf
会将我的浮点值四舍五入到0.5步的下一个最高值。例如,1.5f
将四舍五入为2.0f
我试过了,但代码告诉我不是这样:
int roundUp = 1.5f;
NSLog(@"no round up: %d", roundUp);
NSLog(@"lroundf: %ld", lroundf(roundUp));
我的输出是:
no round up: 1
lroundf: 1
如何正确地对浮点进行取整?首先使用
float
(或double
)而不是int
…*facepalm*。。。对不起,谢谢!如果OP实际上有theFloat
而不是theInt
,这将更有用。他问如何正确地将float四舍五入。我以为他做得对。现在我知道他错了。
int rounded = lroundf(theFloat); NSLog(@"%d",rounded);
int roundedUp = ceil(theFloat); NSLog(@"%d",roundedUp);
int roundedDown = floor(theFloat); NSLog(@"%d",roundedDown);