How to make this fraction addition operator work?

110 views Asked by At
  Fraction &operator+= (const Fraction &obj){
    if (denom == obj.denom){
      num += obj.num;
    }
    else{   
      lcm = l_c_m(num, denom);
      num * (lcm / denom) += obj.num * (lcm / obj.denom);
    }
    return *this;  //returns current object
  }

//calculating highest common denominator
int g_c_d(int n, int d){
    return d == 0? n : g_c_d(d, n % d);
 }

int l_c_m(int a, int b){
  int temp = g_c_d(a, b);
  return temp ? (a / (temp * b)) : 0;
    }

int main(){
   cout << frac1 << " +  " << frac2 << " = ";
   cout << (frac1 += frac2) << endl;
   }

I am trying to add fractions using this code. Hoever the overloaded addition operator doesnt work when the denominators are different. But the code does work when the denominators are the same.

5

There are 5 answers

2
Jonathan Mee On

If you meant to do: lcm = lcm(obj.denom, denom);

Then you need to change this line: num * (lcm / denom) += obj.num * (lcm / obj.denom);

To this: num = num * (lcm / denom) + obj.num * (lcm / obj.denom);

Incidentally you'll also need to update your denom. denom = lcm;

3
3Demon On

You seriously mean this ? :-O

num * (lcm / denom) += obj.num * (lcm / obj.denom);

do it right :-

num = num * (lcm / denom) + obj.num * (lcm / obj.denom);
2
Jarod42 On

Your function should look something like

Fraction &operator+= (const Fraction &obj){
    if (denom == obj.denom){
        num += obj.num;
    } else {
        num = num * obj.denom + obj.num * denom;
        denom *= obj.denom;
    }
    normalize(); // simplify num and obj
    return *this;  //returns current object
}
0
Steephen On

lcm = l_c_m(obj.denom, denom); num = num * (lcm / denom) + obj.num * (lcm / obj.denom);

1
batuhan On

I think that the code should be like this

Fraction &operator+= (const Fraction &obj){
if (denom == obj.denom){
  num += obj.num;
}
else{   
  lcm = l_c_m(obj.denom, denom);
 num= num * (lcm / denom) + obj.num * (lcm / obj.denom);
}
return *this;  //returns current object

}