Integer rounding in C++

user3064203 picture user3064203 · Jan 22, 2014 · Viewed 28.4k times · Source

I was trying to use the formula below in c++. I have both variables declared as integers and I'm expecting them to round up but they seem to be rounding down. I have looked over this but cannot seem to find what is wrong. Any help would be greatly appreciated.

int user_degrees_latitude, user_degrees_longitude;
const int lat_const=(-90)
const int long_const=(-180)

sector_latitude = (user_degrees_latitude - lat_const) / (10);
sector_longitude = (user_degrees_longitude - long_const) / (10);

The answer should be 13 for sector_latitude and 11 for sector_longitude but the computer rounds each down to 12 and 10 respectively.

Answer

Glenn picture Glenn · Jan 22, 2014

In C++, integers are not rounded. Instead, integer division truncates (read: always rounds towards zero) the remainder of the division.

If you want to get a rounding effect for positive integers, you could write:

sector_latitude = static_cast<int>(((user_degrees_latitude - lat_const) / (10.0)) + 0.5);

The addition of 0.5 causes the truncation to produce a rounding effect. Note the addition of the .0 on 10.0 to force a floating point divide before the addition.

I also assumed that sector_latitude was an int with the casting.