In this lecture, we are going to facilitate the expressions below
2/3 + 5.6
4 + 8/17
In which, the first one is the addition of a Fraction
and a double
while the second one is the addition of an int
and a Fraction
. In the first case, we need to convert a Fraction
to a double
and then perform the addition for double
's, while in the second case we convert an int
to a Fraction
and then perform the addition for Fraction
's.
operator double()
without a returning type (not even void
) just like constructors.Fraction(int)
that converts the given int
to a Fraction
.Fraction()
that takes no argument.
int main() {
Fraction num1, num2;
double x;
int y;
char oper1, oper2;
cin >> num1 >> oper1 >> x;
cin.ignore(1024, ',');
cin >> y >> oper2 >> num2;
switch (oper1) {
case '+':
cout << '(' << num1 << ") + (" << x << ") = "<< (double)num1 + x << endl; break;
case '-':
cout << '(' << num1 << ") - (" << x << ") = "<< (double)num1 - x << endl; break;
case '*':
cout << '(' << num1 << ") * (" << x << ") = "<< (double)num1 * x << endl; break;
case '/':
cout << '(' << num1 << ") / (" << x << ") = "<< (double)num1 / x << endl; break;
}
switch (oper2) {
case '+':
cout << '(' << y << ") + (" << num2 << ") = "<< (Fraction)y + num2 << endl; break;
case '-':
cout << '(' << y << ") - (" << num2 << ") = "<< (Fraction)y - num2 << endl; break;
case '*':
cout << '(' << y << ") * (" << num2 << ") = "<< (Fraction)y * num2 << endl; break;
case '/':
cout << '(' << y << ") / (" << num2 << ") = "<< (Fraction)y / num2 << endl; break;
}
return 0;
}
8/17 + 3.4 , 5* 6/17
(8/17) + (3.4) = 3.87059
(5) * (6/17) = 30/17
9/38 / 7.234,18- 634/29
(9/38) / (7.234) = 0.0327401
(18) - (634/29) = -112/29