如何通过舍入到最接近的整数将float转换为Int

时间:2010-01-10 03:15:38

标签: type-conversion

有没有办法通过舍入到最接近的整数整数将float转换为Int

5 个答案:

答案 0 :(得分:57)

舍入到最近的使用roundf(),向上舍入使用ceilf(),向下舍入使用floorf()。希望这个例子能够证明......

#import "math.h"

...

float numberToRound;
int result;

numberToRound = 4.51;

result = (int)roundf(numberToRound);
NSLog(@"roundf(%f) = %d", numberToRound, result); // roundf(4.510000) = 5

result = (int)ceilf(numberToRound);
NSLog(@"ceilf(%f) = %d", numberToRound, result); // ceilf(4.510000) = 5

result = (int)floorf(numberToRound);
NSLog(@"floorf(%f) = %d", numberToRound, result); // floorf(4.510000) = 4


numberToRound = 10.49;

result = (int)roundf(numberToRound);
NSLog(@"roundf(%f) = %d", numberToRound, result); // roundf(10.490000) = 10

result = (int)ceilf(numberToRound);
NSLog(@"ceilf(%f) = %d", numberToRound, result); // ceilf(10.490000) = 11

result = (int)floorf(numberToRound);
NSLog(@"floorf(%f) = %d", numberToRound, result); // floorf(10.490000) = 10


numberToRound = -2.49;

result = (int)roundf(numberToRound);
NSLog(@"roundf(%f) = %d", numberToRound, result); // roundf(-2.490000) = -2

result = (int)ceilf(numberToRound);
NSLog(@"ceilf(%f) = %d", numberToRound, result); // ceilf(-2.490000) = -2

result = (int)floorf(numberToRound);
NSLog(@"floorf(%f) = %d", numberToRound, result); // floorf(-2.490000) = -3

numberToRound = -3.51;

result = (int)roundf(numberToRound);
NSLog(@"roundf(%f) = %d", numberToRound, result); // roundf(-3.510000) = -4

result = (int)ceilf(numberToRound);
NSLog(@"ceilf(%f) = %d", numberToRound, result); // ceilf(-3.510000) = -3

result = (int)floorf(numberToRound);
NSLog(@"floorf(%f) = %d", numberToRound, result); // floorf(-3.510000) = -4

文档......

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/roundf.3.html

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/ceil.3.html

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/floor.3.html

答案 1 :(得分:27)

实际上Paul Beckingham的回答并不完全正确。如果您尝试负数(如-1.51),则得-1而不是-2。

math.h中的函数round(),roundf(),lround()和lroundf()也适用于负数。

答案 2 :(得分:4)

这个怎么样:

float f = 1.51;
int i = (int) (f + 0.5);

答案 3 :(得分:0)

(int)floor(f+0.5);

试试这个......

答案 4 :(得分:0)

round()可以将浮点数四舍五入到最接近的整数,但是它的输出仍然是浮点数...所以将round()的输出强制转换为整数:

float input = 3.456;
int result;

result = (int)round(input);

//结果是:3

Working example for C++ here.