csansoon

P9.09 P93090 F008B. Addition of fractions

Dec 12th, 2018
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. struct Fraction {
  6.     int num, den;   // always strictly positive
  7. };
  8.  
  9.  
  10.  
  11. int gcd (int n, int d) {
  12.     int r = 0;
  13.     if(d == 0)
  14.         return n;
  15.     else {
  16.         r = gcd(d, n%d);
  17.     }
  18.     return r;
  19. }
  20.  
  21.  
  22.  
  23.  
  24. Fraction addition(const Fraction& x, const Fraction& y) {
  25.     Fraction result;
  26.     result.num = (x.num * y.den)+ ( y.num * x.den);
  27.     result.den = x.den * y.den;
  28.     int i = gcd(result.num,result.den);
  29.     result.num = result.num/i;
  30.     result.den = result.den/i;
  31.     return result;
  32. }
  33.  
  34.  
  35. int main() {
  36.     Fraction a,b;
  37.     char c;
  38.     cin>>a.num>>c>>a.den;
  39.     while (cin>>c && c!='=') {
  40.         cin>>b.num>>c>>b.den;
  41.         a = addition(a,b);
  42.     }
  43.     cout<<a.num<<"/"<<a.den<<endl;
  44. }
  45.  
  46. // (c) Carlos Sansón (Best pro1 delegate ever for sure) @csansoon
Advertisement
Add Comment
Please, Sign In to add comment