Hey guys,
I was wondering if you could help me fix my program. I'm witing a program in C++ that adds, subtracts, multiplies and divides fractions. I'm suppose to put in the cosntructor that the denominator cannot be 0 or a negative number and i also I have to reduce the fraction. I have no problem adding, subtracting , etc. When i run it saids that there's no appropriate default constructor available for x, a, and b. Well take a look at my code so, you can see what i mean.
#include <iostream.h>
#include <math.h>
class RationalNumbers
{
public:
RationalNumbers(double, double);
RationalNumbers operator+(const RationalNumbers &) const;
RationalNumbers operator-(const RationalNumbers &) const;
RationalNumbers operator*(const RationalNumbers &) const;
RationalNumbers operator/(const RationalNumbers &) const;
friend ostream &operator<<(ostream&, const RationalNumbers &);
friend istream &operator>>(istream&, RationalNumbers & );
private:
double numerator;
double denominator;
};
// Constructor
RationalNumbers::RationalNumbers( double num, double den )
{
num=numerator;
if (den>0)
{den=denominator;}
}
//void RationalNumbers::reduce()
//{}
// addition
RationalNumbers RationalNumbers::operator+( const RationalNumbers &part2 ) const
{
return RationalNumbers( numerator*part2.denominator+part2.numerator*denominator,
denominator*part2.denominator );
}
// subtraction
RationalNumbers RationalNumbers::operator-( const RationalNumbers &part2 ) const
{
return RationalNumbers( numerator*part2.denominator-part2.numerator*denominator,
denominator*part2.denominator );
}
//multiplication
RationalNumbers RationalNumbers::operator *( const RationalNumbers &part2 ) const
{
return RationalNumbers(numerator*part2.numerator, denominator*part2.denominator);
}
//Division
RationalNumbers RationalNumbers::operator /(const RationalNumbers &part2) const
{
return RationalNumbers(numerator*part2.denominator, denominator*part2.numerator);
}
istream &operator>>(istream &in, RationalNumbers &part2)
{
in>>part2.numerator;
in.ignore();
in>>part2.denominator ;
return in;
}
// show form: (a, b)
ostream &operator <<(ostream &out, const RationalNumbers &part2)
{out<<part2.numerator<<"/"<<part2.denominator <<endl;
return out;
}
int main()
{
RationalNumbers x;
RationalNumbers a;
RationalNumbers b;
cout<<"Enter 2 integers for a:\n";
cin>>a;
cout<<"\nEnter 2 integers for b:\n";
cin>>b;
cout<<"x = a + b: ";
x=a+b;
cout<<x;
cout<<"x = a - b: ";
x=a-b;
cout<<x;
cout<<"x = a*b: ";
x=a*b;
cout<<x;
cout<<"x=a/b: ";
x=a/b;
cout<<x;
return 0;
}