Adding rationals with overloading operators

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

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
 #include <iostream>
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:

24
25
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: +
Topic archived. No new replies allowed.