Challenge: Adding Fractions
Completed
Write a struct Fraction with int num, den, an operator+ and an operator<< that prints it as num/den. The result must be in lowest terms (divide by the greatest common divisor). Read two fractions as a b c d (meaning a/b and c/d) and print their sum.
Input
Four positive integers a b c d.
Output
The sum, like 5/6.
Example
Input
1 2 1 3
Output
5/6
Editor
C++
Hints
a/b + c/d = (a*d + c*b) / (b*d).
Divide top and bottom by gcd(top, bottom).
operator<< returns ostream& and takes (ostream& out, const Fraction& f).
Solution explanation
With operator+ and operator<< the fraction behaves like a built-in type: cout << x + y just works.
Show solution
#include <iostream>
using namespace std;
int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
struct Fraction {
int num;
int den;
Fraction operator+(const Fraction& o) const {
int n = num * o.den + o.num * den;
int d = den * o.den;
int g = gcd(n, d);
return {n / g, d / g};
}
};
ostream& operator<<(ostream& out, const Fraction& f) {
out << f.num << "/" << f.den;
return out;
}
int main() {
Fraction x, y;
cin >> x.num >> x.den >> y.num >> y.den;
cout << x + y << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module