I've spent the last couple of hours trying to find a solution to my problem online, and couldn't. For the record, I am a beginner and probably make loads of mistakes, I would like to ask for a help with one issue: I'm trying to write program, that will add two fractions and show me the results. For example, I have entered "5/11" and "3/11", and I want it to dispay "8/11". However, it gives me "0/1" I've overloaded "+" and ">>" operators, but I'm not sure if I did it correctly. Here's the code:
#include <iostream>
using namespace std;
class fraction
{
public:
int num;
int den;
int sign;
fraction (int top);
fraction (int top, int bot);
};
ostream& operator<< (ostream& z , fraction u) {
if (u.sign==-1) z<<"-";
z<<u.num<<"/"<<u.den;
return z;
}
fraction operator+ (fraction x, fraction y) {
x.num*y.den+y.num*x.den;
return 0; }
fraction::fraction (int top, int bot)
{
den=bot;
num=top;
sign=1;
if (bot<0)
{
sign=-sign;
den=-den;
}
if (top<0)
{
sign=-sign;
num=-num;
}
if (bot==0)
{
num=0;
den=1;
sign=1;
}
}
fraction::fraction (int top)
{
den=1;
num=top;
sign=1;
if (top<0)
{
sign=-sign;
num=-num;
}
}
int main() {
fraction x (5,11),y (4,11);
cout<<x<<" "<<y;
cout<<" x+y= "<<x+y;
return 0;
}
Specifically, I believe the problem lies in two spots:
fraction operator+ (fraction x, fraction y) {
x.num*y.den+y.num*x.den;
return 0; }
And:
int main() {
fraction x (5,11),y (4,11);
cout<<x<<" "<<y;
cout<<" x+y= "<<x+y;
return 0;
}
I know "return 0" in the overload is wrong, but I have no idea what to replace it with. Any help would be really appreciated!
fraction operator+ (fraction x, fraction y) {
return fraction(x.num*y.den+y.num*x.den,x.den*y.den); }