Search code examples
c++error-handlingdivide-by-zero

Division by Zero Error in a Simple Program


For whatever reason a simple test program is generating division by zero errors even though division by zero is impossible as far as I can tell:

#include <iostream>

using namespace std;

int main()
{
    int Level = 1;
    int EXPTNL = 0;

    cout << Level << endl;

    EXPTNL = (Level * 1250) * 1000 * 1000 * Level / (2 / ((1000 * (Level * 1250)) / 2));

    cout << EXPTNL << endl;

    system("Pause");
}

Am I missing something? This exact same formula works just fine in another, much more complex, program.


Solution

  • This will almost certainly lead to a zero value:

    (2 / ((1000 * (Level * 1250))
    

    if level is non-zero, 1000 * (Level * 1250), is much larger than 2, which in integer division will give the result zero.

    Maybe you want to use a floating point value so that your EXPTNL becomes a floating point calculation, and then make it an integer at the end.

    I also expect (Level * 1250) * 1000 * 1000 to oveflow a 32-bit integer, so you probably want that as a floating point calculation.

    Just make each of the 1250 values into a 1250.0 and problem solved.