I have the folowing example :
double x = 2.5;
int n = (int)x;
int k = (int) floor(x);
Does casting double to int returns the round down number? or I should use floor function?
I have the folowing example :
double x = 2.5;
int n = (int)x;
int k = (int) floor(x);
Does casting double to int returns the round down number? or I should use floor function?
Be careful with negative numbers. Casting will truncate towards 0. floor
will truncate towards negative infinite.
If the value is positive, then both methods return the same truncated value.
Well (int)
truncates the initial double
value (fractional part removed)
2.1 -> 2
2.5 -> 2
2.99 -> 2
it looks like floor
, but they're not the same in case of negative numbers:
(int)-2.1 -> -2
floor(-2.1) -> -3.0
since floor
returns max integer value that less or equal to the given argument
Beware of the limitation of int and double.
int main(void)
{
double val1 = INT_MAX + 10.5;
int val2 = val1;
printf("val1 = %f\nval2 = %d\n", val1, val2);
return (0);
}
This produce the output below :
val1 = 2147483657.500000
val2 = -2147483648
(I don't know if INT_MAX is standard, sorry).