Overload operators

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
using namespace std;
class FRACT
{
private: int n, d;
public: void ReadFract()
	{
		cout << "Enter a fraction: ";
		cin >> n; cin.ignore();
		cout << "Enter another fraction: "; cin >> d;
	}
//display the data
		void DisplayFract()
	{
			cout << n << '/' << d;
	}

//overload addition operator
friend FRACT operator +(FRACT F2, FRACT F1)
{
	FRACT r;

	// r.n/r.d = F2.n/F2.d + F1.n/F1.d 
	// = (F2.n * F1.d + F2.d * F1.n) / (F2.d * F1.d) 

	r.n = F2.n * F1.d + F2.d * F1.n; 
	r.d = F2.d * F1.d;
	return r;
}
//create a member to find F1-F2
FRACT operator - (FRACT F2)
{
	FRACT r;
	// r.n / r.d = n / d - F2.n / F2.d

	r.n = F2.d * n - F2.n * d;
	r.d = d * F2.d;
	return r;
}
//create a member to find F1 * F2
FRACT operator * (FRACT F2)
{
	FRACT r;
	// r.n / r.d = n / d * F2.n / F2.d

	r.n = F2.n * n;
	r.d = d * F2.d;
	return r;
}
//determine if true or false
friend bool operator < (FRACT F2, FRACT F1)
{
	bool TrueFalse;
	if(F2.n * F1.d < F2.d *F1.n) return (cout << "TRUE");
	else return (cout << "FALSE");
}

};

int main()
{
	bool TrueFalse;
	
	char again;
	FRACT f1, f2;
	do
	{
	f1.ReadFract();
	f2.ReadFract();
	FRACT R = f1 + f2;
	FRACT R2 = f1 - f2;
	FRACT R3 = f1 * f2;
	
	f1.DisplayFract();
	cout << " + "; f2.DisplayFract(); cout << " = "; 
	R.DisplayFract();
	cout << endl;
	//subtract operator
	f1.DisplayFract();
	cout << " - "; f2.DisplayFract(); cout << " = "; 
	R2.DisplayFract();
	cout << endl;
	f1.DisplayFract();
	cout << " * "; f2.DisplayFract(); cout << " = "; 
	R3.DisplayFract();
	cout << endl;
	f1.DisplayFract();
	cout << " < "; f2.DisplayFract(); cout << " is ";
	bool TrueFalse = f1 < f2;
	cout << endl;
	cout << "CONTINUE(y/n)? "; cin >> again;
	}while( again == 'y' || again == 'Y');

	system("PAUSE");
	return 0;
}


Enter a fraction comes two times, how do I fix this? I tried a for loop in the read function but it comes out even worse.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Enter a fraction: 2/3
Enter another fraction: Enter a fraction: 4/5
Enter another fraction: 2/3 + 4/5 = 22/15
2/3 - 4/5 = -2/15
2/3 * 4/5 = 8/15
2/3 < 4/5 is TRUE
CONTINUE(y/n)? y
Enter a fraction: 7/3
Enter another fraction: Enter a fraction: 4/5
Enter another fraction: 7/3 + 4/5 = 47/15
7/3 - 4/5 = 23/15
7/3 * 4/5 = 28/15
7/3 < 4/5 is FALSE
CONTINUE(y/n)? n
Press any key to continue . . .
Last edited on
you cannot store
2/3
on an int
you need to have separete var for integer and operator
Topic archived. No new replies allowed.