Does listing double to int perform a rounded number?

I have the following example:

double x = 2.5;
int n = (int)x;
int k = (int) floor(x);

Does listing double to int perform a rounded number? or should i use the gender function?

+4
source share
3 answers

Be careful with negative numbers. Casting will be truncated in the direction of 0. It floorwill truncate in the direction of the negative infinite.

If the value is positive, both methods return the same truncated value.

+13
source

Well, (int)truncates the initial value double(fractional part removed)

  2.1  -> 2
  2.5  -> 2
  2.99 -> 2

it looks like floor, but they do not match in the case of negative numbers:

  (int)-2.1   -> -2
  floor(-2.1) -> -3.0

floor ,

+7

Beware of int and double constraints.

int main(void)
{
    double val1 = INT_MAX + 10.5;
    int    val2 = val1;

    printf("val1 = %f\nval2 = %d\n", val1, val2);

    return (0);
}

The following data is displayed here:

val1 = 2147483657.500000
val2 = -2147483648

(I don't know if INT_MAX is standard, sorry).

0
source

Source: https://habr.com/ru/post/1628536/


All Articles