Подтвердить что ты не робот

Как преобразовать float в Int путем округления до ближайшего целого целого

Есть ли способ конвертировать float в Int путем округления до ближайшего целого целого числа?

4b9b3361

Ответ 1

Собственно, ответ Пола Бэкингхэма не совсем корректен. Если вы попробуете отрицательное число, например -1.51, вы получите -1 вместо -2.

Функции round(), roundf(), lround() и lroundf() из math.h работают и для отрицательных чисел.

Ответ 2

Чтобы округлить до ближайшего использования 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

Ответ 3

Как насчет этого:

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

Ответ 4

(int)floor(f+0.5);

Попробуйте это...