Handling overflow when casting doubles to integers in C

后端 未结 9 2056
耶瑟儿~
耶瑟儿~ 2020-12-09 08:24

Today, I noticed that when I cast a double that is greater than the maximum possible integer to an integer, I get -2147483648. Similarly, when I cast a double that is less

9条回答
  •  情话喂你
    2020-12-09 09:23

    limits.h has constants for max and min possible values for integer data types, you can check your double variable before casting, like

    if (my_double > nextafter(INT_MAX, 0) || my_double < nextafter(INT_MIN, 0))
        printf("Overflow!");
    else
        my_int = (int)my_double;
    

    EDIT: nextafter() will solve the problem mentioned by nwellnhof

提交回复
热议问题