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

前端 未结 3 1307
温柔的废话
温柔的废话 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:32

    The way to fix this is to static_cast because long long is 8 bytes and it is large enough to hold the information in the event of an overflow. An overflow occurs when you try to hold a number when you do not have enough bits to do so and as a result some of them get chopped off.

    Here is an example without the warning:

    std::cout << "Two roots: " << (-b - std::sqrt(d)) / (2 * static_cast(a)) << " "
              << (-b + std::sqrt(d)) / (2 * static_cast(a));
    
    

提交回复
热议问题