Arithmetic overflow: Using operator '*' on a 4 byte value then casting the result to a 8 byte value

前端 未结 3 1335
温柔的废话
温柔的废话 2021-01-24 08:08

I am trying to write a program to solve a quadratic equation whose coefficients\' values do not exceed 100 by absolute value and it is guaranteed that if any roots exist, they a

3条回答
  •  不要未来只要你来
    2021-01-24 08:14

    It's not a bug. Here:

    (-b - std::sqrt(d)) / (2 * a)
    

    The result of the expression is a double. But result of 2 * a is an int and it's eventually converted to a double. It is possible that 2 * a overflows if a is too large before it's converted to double. But since the eventual result is already a double, you could cast 2 or a to double as well and avoid the risk of overflow once and for all. So the compiler is telling you that the Right ThingTM to do is:

    (-b - std::sqrt(d)) / (2.0 * a)
    

    It won't overflow (result of (2.0 * a) is a double) and it's probably already what you want.

提交回复
热议问题