Private float value ios
I have a value, for example int value1 = 11
after dividing by 2 ( value1 / 2
) it returns 5. The real value in float is 5.5, can anyone help me return 6 in this case or other case ..? In general, I want to round up the value to the next one above.
If you always want to round and have a value float
, use ceilf
(from library <math.h>
).
If you want to round an integer division by n
, do (value + n-1) / n
. So, for division by 2, this becomes (value + 1) / 2
.
there are ceil (<# (double) #>) or ceilf (<# (float) #>) functions that round the value up
Also, you must explicitly use float / double calculations to get 5.5, which can be rounded up.
ceilf(value1 / 2.0f);
or
ceilf(1.0f * value1 / 2);
If you don't, it can be presented in the following sequence:
ceilf(11/2) =
1) 11/2 = result int = 5
2) ceilf(5)
3) 5 ->int implicitly cast to float -> 5.0f
4) result 5.0f
Well, usually, you just add 1:
int half = (value1 + 1) / 2
So you will always round up. Should be the easiest way for integers.
ceil(value1 / 2)
Rounds to nearest int