Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

This is integer division:

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

and, since the denominator's magnitude is larger than that of the numerator, you get 0.

It would have been easy to test this:

std::cout << (2 / ((1000 * (Level * 1250)) / 2)) << std::endl;

You need floating point division, which you can get by having a floating point number in the numerator or denominator (or both).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top