I was curious to know how I can round a number to the nearest tenth whole number. For instance, if I had:
int a = 59 / 4;
which would be 14.75 calculated in floating point; how can I store the number as 15 in "a"?
I was curious to know how I can round a number to the nearest tenth whole number. For instance, if I had:
int a = 59 / 4;
which would be 14.75 calculated in floating point; how can I store the number as 15 in "a"?
The standard idiom for integer rounding up is:
int a = (59 + (4 - 1)) / 4;
You add the divisor minus one to the dividend.
int a = 59.0f / 4.0f + 0.5f;
This only works when assigning to an int as it discards anything after the '.'
As written, you're performing integer arithmetic, which automatically just truncates any decimal results. To perform floating point arithmetic, either change the constants to be floating point values:
int a = round(59.0 / 4);
Or cast them to a float
or other floating point type:
int a = round((float)59 / 4);
Either way, you need to do the final rounding with the round()
function in the math.h
header, so be sure to #include <math.h>
.