What causes a runtime error in this code

148 views Asked by At

I'm working on the UVA problem 12468 Zapping.

I've checked several test cases and it works successfully but when I submit this solution to UVA online judge it judged it as runtime error. Where can the error be? Please explain your answer.

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

int main()
{
    int a,b,next,bk;

    while(true)
    {
        cin >> a >> b;
        if (a == -1 && b == -1)
            break;

        next = abs(a - b);

        if (next > 50)
        {
            bk = (a % b) + 1;

            cout << bk << endl;
        }
        else
        {
            cout << next << endl;
        }
    }

    return 0;
}
1

There are 1 answers

0
Dialecticus On BEST ANSWER

Your question in essence is "how can the following code cause a run time error". The answer to that question is given by πάντα ῥεῖ, and it happens on line (a%b)+1 when variable b is equal to zero.

But if the actual question is "how to change the code so that it gives the correct output according to problem 12468 description" then the answer should be to replace that line with the following:

bk = 100 - next;

So if zapping the remote in one direction takes more than half of the maximum this tells you how much will it take zapping it in the opposite direction.