I'm close to getting the code right, but I'm missing something. Anytime I add a rational with the same denominator it works fine, but I need a little help with when it doesn't have the same denominator. I'm sure it has to do with the else statement, but don't know what it is exactly.

For example:
First rational is 1/3
Second rational is 1/6
Says the addition is 3/18 when it should be 9/18

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081`` `````` #include using namespace std; class Rational { public: Rational(); Rational(int d, int n); void ReadRational(); void display(); Rational operator +(Rational r) { Rational temp; if (denom == r.denom)//making sure if both denominators are the same they stay the same { temp.num = num + r.num; temp.denom = denom = r.denom; temp.denom = r.denom = denom; } else { temp.denom = denom * r.denom; temp.num = num * r.denom; temp.num = r.num * denom; } return temp; } private: int num = 0; int denom = 1; }; Rational::Rational() { } Rational::Rational(int d, int n) { num = 0; denom = 1; } int main() { int d, n; Rational r1, r2;//r in this case will be short for rational r1.ReadRational(); cout << "First rational is "; r1.display();//since num and denom are private I call upon this since it is part of the class r2.ReadRational(); cout << "Second rational is "; r2.display(); Rational Sum = r1 + r2; Sum.display(); } void Rational::display() { cout << num << "/" << denom << endl; } void Rational::ReadRational() { cout << "Enter in the numerator: "; cin >> num; cout << endl; cout << "Enter in the denominator (do not put zero in): "; cin >> denom; if (denom == 0) { cout << "Invalid input!" << endl; exit(1); } }``````
Last edited on
Look at lines 24 and 25:

 ``2425`` ``````temp.num = num * r.denom; temp.num = r.num * denom;``````

You set a value in temp.num, and then you immediately throw it away and overwrite it with a different number.

If you learnt how to use your debugger to step through your code, you'd have been able to see this for yourself.
Last edited on
Thanks for the input! I just figured that out and found a solution. I created temp2 to hold the other formula and did this:
 `` `` ``temp.num += temp2.num;``

Line 25 simply overwrites the value from line 24. I guess you want line 25:

`temp.num += r.num * denom; // Note: + `