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

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
It's the same as in C, so n=1.
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);
The Palm Tree Magician wrote:
C++ always truncates, aka rounds down.

That's not true for negative numbers. It rounds towards zero.
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
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.