-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathprogram 6 oops.cpp
More file actions
95 lines (94 loc) · 1.83 KB
/
Copy pathprogram 6 oops.cpp
File metadata and controls
95 lines (94 loc) · 1.83 KB
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
#include<iostream>
using namespace std;
class Rational{
float num,denom;
public:
Rational()
{
}
Rational(float num, float denom)
{
if(denom==0)
{
cout << "Denominator can't be zero";
exit(1);
}
this->num = num;
this->denom = denom;
}
Rational reduce()
{
Rational temp;
int h = hcf(num, denom);
temp.num = num/h;
temp.denom = denom/h;
return temp;
}
Rational operator +(Rational r)
{
Rational ans;
ans.denom = denom*r.denom;
ans.num = num*r.denom+r.num*denom;
return ans;
}
int hcf(int a, int b);
friend istream& operator >>(istream& s, Rational& r);
friend ostream& operator <<(ostream& s, Rational& r);
};
int Rational::hcf(int a, int b)
{
int r;
r = a%b;
while(r)
{
a=b;
b=r;
r=a%b;
}
return b;
}
istream& operator >>(istream& s,Rational& r)
{
int a,b;
char c;
s>>a>>c>>b;
if(c!='/')
{
cout<<"use of invalid notation";
exit(0);
}
if(b==0)
{
cout<<"denominator can't be zero.";
exit(1);
}
r.num=a;
r.denom=b;
return s;
}
ostream& operator <<(ostream& s,Rational& r)
{
if(r.denom==1)
s<<r.num;
else
{
if(r.denom==-1)
s<<-r.num;
else
s<<r.num<<'/'<<r.denom;
}
return s;
}
int main()
{
Rational r1,r2,r3;
cout<<"enter r1:";
cin>>r1;
cout<<"enter r2:";
cin>>r2;
r3=r1+r2;
cout<<r1<<" + "<<r2<<" = "<<r3<<" = ";
r3 = r3.reduce();
cout<<r3<<endl;
return 0;
}