简体   繁体   中英

Integer rounding in C++

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);

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.

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.

Although this thread is very old, I am saddened to see both existing answers converting to floating point then back to integer. If you want to divide n by d and round the quotient to the nearest integer, all using integer-only arithmetic, then you simply add d/2 before dividing:

q = (n + d/2) / d

(Of course, d/2 could be written d>>1 , but the compiler will do that for you.) So, if n is 19 and d is 4, the exact quotient would be 4.75, n/d would yield 4 (truncation towards zero), but the formula above would yield 5, which is the desired result. For the example given in the OP, simply update the last two lines as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM