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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>

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:

1
2
3
4
bool is_equal(rational a, rational b) {
  return static_cast<long long>(a.numerator) * b.denominator ==
         static_cast<long long>(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.