Look at this code please:
#include <iostream>
using namespace std;
class Ratio
{
public:
Ratio(int a=0, int b=1) : num(a), den(b) {}
Ratio& operator/=(const Ratio&);
void print() {cout << num << "/" << den << endl;}
private:
int num, den;
};
Ratio& Ratio::operator/=(const Ratio& r)
{
num*=r.den;
den*=r.num;
return *this;
}
int main()
{
Ratio x(1,2), y(2,5);
y/=x;
y.print();
}
after executing this code, (y) should be 5/4, I have calculate it several times by my hands! But in output after printing (y), it shows 4/5! It is inverted by it should not be!
Where is the problem with my code? really I have checked it several and several times and it seems it does not have any problem! It is a homework 🙂
How did you decide it should be 5/4? (2/5) / (1/2) = 4/5 and it is correct result. Maybe you are calculating x/=y instead when you expect 5/4.