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.
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;