I am trying to compare two rational numbers to see if they are equal or not, but there is a logic error. For example, 1/5 and 5/25 will give me an equal, but 1/5 and 6/7 will also give me an equal.
You're doing integer division: 1/5 and 6/7 will both equate to 0, because integer division throws away the remainder. Try casting the values to float or double.
But this is prone to errors because floating point mathematics suffers from precision issues. In particular, the exact arithmetic properties of floating point shouldn't be relied on unless you're an expert. The details are complex and subtle.
Instead of adding casts to float, note that a/b = c/d --> ad = bc. You can simply perform multiplications, casting to longlong to avoid potential signed overflow:
1 2 3 4
bool is_equal(rational a, rational b) {
returnstatic_cast<longlong>(a.numerator) * b.denominator ==
static_cast<longlong>(a.denominator) * b.numerator;
}
Comparing floating-point numbers for equality is dangerous because of finite precision, particularly if they have come from different division operations.
Use the fact that a/b = c/d if ad=bc.
No integer division involved and you will be comparing two integers.