Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer rounding in C++

Tags:

c++

int

cmath

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.

like image 289
user3064203 Avatar asked Dec 09 '22 10:12

user3064203


2 Answers

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.

like image 80
Glenn Avatar answered Dec 25 '22 20:12

Glenn


Integer division in C++ always rounds towards zero. Use floating-point division to get "exact" results and use std::round to round according to the normal rules:

sector_latitude = static_cast</*type of sector_latitude*/>( std::round( (user_degrees_latitude - lat_const) / 10.0 ));

The "10.0" (a double) instead of "10" (an int) tells the compiler to use floating-point arithmetic. It always chooses floating-point over integer calculation if a floating-point value like a double is involved.

like image 40
Baum mit Augen Avatar answered Dec 25 '22 20:12

Baum mit Augen