This repository has been archived by the owner on Mar 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fract.cpp
144 lines (97 loc) · 2.3 KB
/
fract.cpp
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// Jerred Shepherd
#include <iostream>
using namespace std;
int gcd(int x, int y) {
int t;
t = x % y;
while (t != 0) {
x = y;
y = t;
t = x % y;
}
return y;
}
int lcm(int x, int y) {
int cnt, ans;
if (x > y) {
cnt = x;
}
else {
cnt = y;
}
ans = 0;
while (ans == 0) {
if (cnt % x == 0 && cnt % y == 0) {
ans = cnt;
}
else {
cnt++;
}
}
return ans;
}
void reduce(int &num, int &den) {
int divisor;
divisor = gcd(num, den);
num = num / divisor;
den = den / divisor;
}
void common_den(int &num1, int &den1, int &num2, int &den2) {
int cden;
cden = lcm(den1, den2);
num2 *= cden / den2;
num1 *= cden / den1;
den1 = cden;
den2 = cden;
}
void main()
{
int num1, den1, num2, den2, newnum, newden;
char slash1, slash2, op;
cout << "\nFraction Calculator\n\n";
cout << "Add, subtract, multiply & divide - positive fractions only\n";
cout << "Enter '0/0 + 0/0' to quit.\n";
// Input will be assumed to be in correct form for simplification
// Input data before loop in case they want to exit right away
cout << "\n> ";
cin >> num1 >> slash1 >> den1 >> op >> num2 >> slash2 >> den2;
while (num1 + den1 + num2 + den2 > 0)
{
// Reduce both fractions to keep integers as small as possible
reduce(num1, den1);
reduce(num2, den2);
switch (op) {
case '+':
// Find common denominator and add
common_den(num1, den1, num2, den2);
newnum = num1 + num2;
newden = den1;
break;
case '-':
// Find common denominator and subtract
common_den(num1, den1, num2, den2);
newnum = num1 - num2;
newden = den1;
break;
case '*':
// Multiply numerators and multiply denominators
newnum = num1 * num2;
newden = den1 * den2;
break;
case '/':
// Invert and multiply
newnum = num1 * den2;
newden = den1 * num2;
}
// Reduce the answer to lowest terms
reduce(newnum, newden);
// Output the results
cout << num1 << "/" << den1 << " " << op << " ";
cout << num2 << "/" << den2 << " = ";
cout << newnum << "/" << newden << endl;
// Input data for next iteration of loop
cout << "\n> ";
cin >> num1 >> slash1 >> den1 >> op >> num2 >> slash2 >> den2;
}
system("pause");
}