### To Compare two rational numbers

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.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748`` ``````#include using namespace std; struct rational { int numerator; int denominator; }; bool isEqual(rational num1, rational num2) { if (num1.numerator/num1.denominator == num2.numerator/num2.denominator) { return true; } else { return false; } } int main() { bool result; struct rational num1, num2; cout << "Enter Details of Number 1 " << endl; cout << "Enter Numerator :" << endl; cin >> num1.numerator; cout << "Enter Denominator :" << endl; cin >> num1.denominator; cout << "Enter Details of Number 2 " << endl; cout << "Enter Numerator :" << endl; cin >> num2.numerator; cout << "Enter Denominator :" << endl; cin >> num2.denominator; result = isEqual(num1, num2); //to check rational 'num1' is equal to rational 'num2' if(result == true) { cout << "Both rational numbers are equal" << endl; } else { cout << "Both rational numbers are not equal" << endl; } return 0; } ``````
Last edited on
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.
Thanks for the help!
 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 `long long` to avoid potential signed overflow:

 ``1234`` ``````bool is_equal(rational a, rational b) { return static_cast(a.numerator) * b.denominator == static_cast(a.denominator) * b.numerator; }``````
Last edited on
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.
Topic archived. No new replies allowed.