Álvaro
Álvaro

Reputation: 141

Illegal instruction in while loop c++

I've been assigned to write a program that simplifies a rational number. What I want to do is compute the gcd and then divide the numbers by gcd. But the program returns a very strange error.

The code:

void read_rational(int& num, int& den) {
    char bar;
    if (cin >> num >> bar >> den) {
        cout << "hi";
        int a = num;
        int b = den;
        while (b != 0) {
            int r = a%b;
            a = b;
            b = r;
        }
        num /= b;
        den /= b;
    }
}

INPUT: 10/2  OUTPUT: Illegal instruction (core dumped)
INPUT: 90/8  OUTPUT: Illegal instruction (core dumped)

I've tried commenting out some bits of the script. The program seems to crash only when the while loop is present. But I can't see what's wrong with it.

Upvotes: 3

Views: 2874

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

Indeed, the issue is the while loop. After it finishes, b is actually 0, so the divisions after raise these errors. I think what you want is a instead of b.

Upvotes: 9

Related Questions