I'm close to getting the code right, but I'm missing something. Anytime I add a rational with the same denominator it works fine, but I need a little help with when it doesn't have the same denominator. I'm sure it has to do with the else statement, but don't know what it is exactly.
For example:
First rational is 1/3
Second rational is 1/6
Says the addition is 3/18 when it should be 9/18
#include <iostream>
usingnamespace std;
class Rational
{
public:
Rational();
Rational(int d, int n);
void ReadRational();
void display();
Rational operator +(Rational r)
{
Rational temp;
if (denom == r.denom)//making sure if both denominators are the same they stay the same
{
temp.num = num + r.num;
temp.denom = denom = r.denom;
temp.denom = r.denom = denom;
}
else
{
temp.denom = denom * r.denom;
temp.num = num * r.denom;
temp.num = r.num * denom;
}
return temp;
}
private:
int num = 0;
int denom = 1;
};
Rational::Rational()
{
}
Rational::Rational(int d, int n)
{
num = 0;
denom = 1;
}
int main()
{
int d, n;
Rational r1, r2;//r in this case will be short for rational
r1.ReadRational();
cout << "First rational is ";
r1.display();//since num and denom are private I call upon this since it is part of the class
r2.ReadRational();
cout << "Second rational is ";
r2.display();
Rational Sum = r1 + r2;
Sum.display();
}
void Rational::display()
{
cout << num << "/" << denom << endl;
}
void Rational::ReadRational()
{
cout << "Enter in the numerator: ";
cin >> num;
cout << endl;
cout << "Enter in the denominator (do not put zero in): ";
cin >> denom;
if (denom == 0)
{
cout << "Invalid input!" << endl;
exit(1);
}
}