NZEC error

How to avoid divide by zero error ?

Do not divide by zero :slight_smile:

Actually, if it happens then you could add asserts or some checks in every division you have in the program to find at which exact place error occurs. Then recheck all formulas you have there to avoid this division by zero.

For example like this

#include <iostream>
#include <cassert>
using namespace std;

int main()
{
    int a,b;
    cin >> a >> b;
    assert(b!=0);
    // or if(b==0) for(;;); // to create TL
    cout << a / b;
    return 0;
}

UPD
If you do local test instead of trying to figured it this by submitting to online judge you can quickly find an exact place by putting explanatory printfs for each division instead of simply asserts

#include <iostream>
#include <cassert>
using namespace std;

int main()
{
    int a,b;
    cin >> a >> b;
    if(b==0) {
        fprintf(stderr,"div a/b: %d / %d\n",a,b);
        exit(1);
    }
    cout << a / b;
    int c,d;
    cin >> c >> d;
    if(d==0) {
        fprintf(stderr,"div c/d: %d / %d\n",c,d);
        exit(1);
    }
    cout << c / d;
    return 0;
}
3 Likes

when debugging my code, i use the /// operator for integer division, and i define a macro for it that asserts the denominator part is non-null. :slight_smile: it allows me to kinda factor the code used to check that.

2 Likes

@betlista Thanks for editing my code. Finally I’ve realized how to write code and do not bother that markdown will transform it in some unexpected way.

Nice trick. Does this way allow to find an exact line when this occurs?

Because simply knowing that you have this division by zero while having dozens of divisions in program does not help much :slight_smile:

//