Does C++ round floats to the nearest int when casted into an int?

Feb 3, 2012 at 4:16am
I performed the following casting in C++.

int n = (int) sqrt(3);

The square root of 3 is about 1.732.

When I checked the value of n in gdb, the value I got was 2. Does this mean that casting into an int rounds a float to the nearest integer?

I find this outlandish because c rounds down.

Wait... perhaps I erred. Let me check.
Last edited on Feb 3, 2012 at 4:20am
Feb 3, 2012 at 4:25am
It's the same as in C, so n=1.
Feb 3, 2012 at 4:28am
C++ always truncates, aka rounds down. If you want it to round to the nearest intager, add 0.5 or 0.5f before casting.
 
int n = (int)(sqrt(3)+0.5f);
Feb 3, 2012 at 10:32am
The Palm Tree Magician wrote:
C++ always truncates, aka rounds down.

That's not true for negative numbers. It rounds towards zero.
Feb 3, 2012 at 10:38am
It truncates, the rounding is irrelevant.

Basically, anything after the decimal point is chopped off.

1.7 would become 1.

-3.9 would become -3.
Last edited on Feb 3, 2012 at 10:38am
Feb 3, 2012 at 10:50am
closed account (z05DSL3A)
The Palm Tree Magician is correct in that it truncates. However truncation is just the fractional part is discarded. ... So I guess technically it is rounding towards zero...I'l go back to sleep. ;0)
Topic archived. No new replies allowed.