Reputation: 341
int a, b, c = 0;
c = (a+b)/2;
In this code, if both "a" and "b" are even (Example 1), then there's no problem. But if one of them is odd (Example 2), then the answer will have +0.5. I want to round it up.
Example 1.
a=4, b=10
c will be = 7 This is OK.
Example 2.
a=3, b=4
c will be = 3.5 And I want c to be rounded up and become 4 instead.
Upvotes: 0
Views: 4315
Reputation: 3198
The easiest thing would be to use + 1
after the result if the result is not round (what the ceil
function would do by default for you)
int a, b, c = 0;
if ((a + b) % 2 == 1)
c = ((a+b)/2) + 1;
else
c = (a+b)/2;
Demo: https://ideone.com/AmgDUt
Upvotes: 0
Reputation: 56557
First of all, make c
a double
, then use
c = (a + b)/2.0
otherwise you have truncation due to division of int
s being casted to int
. In this way, (a + b) / 2.0
is a double
, due to the denominator being a double
, so you don't have any truncation.
Next, use the function std::round
from C++11, or std::floor/std::ceil
, depending on what exactly you want
Alternatively, you can keep c
and int
but do
c = std::round( (a + b) / 2.0 ); // rounding to nearest integer, C++11
or
c = std::floor( (a + b) / 2.0 ); // rounding down
or
c = std::ceil( (a + b) / 2.0 ); // rounding up
If you don't want any warnings, can also explicitly cast the result of std::floor/std::ceil/std::round
back to int
, like
c = static_cast<int>(std::round( (a + b) / 2.0 )); // now we tell the compiler we know what we're doing
Upvotes: 0
Reputation: 10385
The simplest thing is to use the ceil()
function from <math.h>
.
int a, b, c = 0;
c = (int) ceil((float)(a+b)/2);
Upvotes: 0
Reputation: 71989
First off, you're wrong. c
is an integer, so it can't be 3.5. Furthermore, a
, b
and 2 are all integers, so the division is integer division, so it can't result in 3.5 either. It will be rounded towards zero, so it will be 3.
That said, to get integer division by 2 to round up instead of down, simply add 1 before dividing. (14 + 1) / 2 == 7
, so that's still right. (7 + 1) / 2 == 4
, so that's correct too.
Upvotes: 8
Reputation: 4638
Use the ceil function. It will always round up whatever number you put in it.
Upvotes: 1