Search code examples
c++divisionoutofrangeexceptionnumeric-limits

INT_MAX divided by twice of itself (INT_MAX * 2)


in C++, I wonder how to get the correct answer 0.5 for "INT_MAX / (INT_MAX + INT_MAX)"? I tried cast the divisor/both divisor and dividend to long, and also cast divisor to double, all return -1073741823. Could anyone give me some advice ? Thanks.


Solution

  • What you are trying is impossible for 2 reasons.

    First, INT_MAX + INT_MAX cannot be represented by an int, which is logical since the maximum value of an int is INT_MAX. This leads to an overflow.

    Second, even if you try to do (3 / (3 + 3)) you will get 0 since you are working with integers and not fractional numbers. Do do what you want to do you can try:

    static_cast<double>(INT_MAX) / (static_cast<double>(INT_MAX) + static_cast<double>(INT_MAX)) though this has no interest.