Rational Number Help

fixed
Last edited on
Remember the rules of fractional numbers.
(a/b) * (c/d) = (a*c) / (b*d)
(a/b) / (c/d) = (a*d) / (b*c)
(a/b) + (c/d) = (a*d + c*b) / (b*d)
(a/b) - (c/d) = (a*d - c*b) / (b*d)
You need to test your class so make up a program that does the sample tests described:

1
2
3
4
5
6
7
8
9
int main()
{
    // 3/8+1/6
    Rational a(3, 8);
    Rational b(1, 6);

    Rational c = a + b;
    std::cout << "3/8+1/6=" << c << std::endl;
}


Make your code compile, then make it produce the right answer.
ok so i updated the 1st post with some provisions , i am still having problems, first i wanted to say thank you for helping i appreciate it. also is my overloading the outputstream correct? because i am trying to test the default constructor but it is not compiling and also is what i done for the implementation for the addition overloading part correct?
anybody? =o
You're missing a fair amount of consts in the class definition:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#ifndef RATIONALNUM_H
#define RATIONALNUM_H

#include <iosfwd>

class Rational
{
private:
    int numerator;
    int denominator;

public:
    Rational();
    Rational(int, int);
    Rational(Rational& obj)
    {
        int numerator = obj.numerator;
        int denominator = obj.denominator;
    }
    void setNumerator(int);
    void setDenominator(int);
    int getNumerator() const;
    int getDenominator() const ;
    Rational operator + (const Rational &obj) const; // overloaded the addition sign
    Rational operator - (const Rational &obj) const; // overloaded the subtraction sign
    Rational operator * (const Rational &obj) const; // overloaded * multiplication sign
    Rational operator / (const Rational &obj) const; // overloaded / division sign
    const Rational& operator = (const Rational &Right);
    friend std::ostream& operator << (std::ostream&, const Rational&);
};

// This doesn't need to be friend, so don't make it one.
std::ostream& operator<<(std::ostream&, const Rational&);

#endif 


Generally you should define +=, -=, *= and /= operators first. operator+, -, * and / may then be defined in terms of those operators.

Last edited on
Topic archived. No new replies allowed.