ADDITION AND DIVISION OPERATOR || CS-1 || EXP-7

write a program in C++ to implement an addition and division operator for the ratio class. hence print the given two ratios x and y , their sum (x+y) and division (x/y).

#include<iostream.h>
#include<conio.h>
class ratio
{
    float x, y;
public:
    ratio() {}
    ratio(float p, float q)
    {
        x = p;
        y = q;
    }
    ratio operator + (ratio);
    ratio operator / (ratio);
    void display(void);
};
ratio ratio::operator + (ratio c)
{
    ratio t;
    t.x = x + c.x;
    t.y = y + c.y;
    return(t);
}

ratio ratio::operator / (ratio c)
{
    ratio t;
    t.x = x / c.x;
    t.y = y / c.y;
    return(t);
}

void ratio::display(void)
{
    cout << "x=" << x << "\t" << "y=" << y;
}

void main()
{
    ratio r1, r2, r3, r4;
    r1 = ratio(2.5, 3.5);
    r2 = ratio(1.6, 2.9);
    r3 = r1 + r2;
    r4 = r1 / r2;
    cout << "r1=";r1.display();cout << "\n";
    cout << "r2=";r2.display();cout << "\n";
    cout << "r3=";r3.display();cout << "\n";
    cout << "r4=";r4.display();
    getch();
}

Leave a Comment

Scroll to Top