0% found this document useful (0 votes)
229 views2 pages

C++ Ratio Class: Addition & Division

Uploaded by

hemanshuganekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
229 views2 pages

C++ Ratio Class: Addition & Division

Uploaded by

hemanshuganekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ADDITION AND DIVISION OPERATOR

Question:
Write a program in C++ to implement the addition and division operators for the `ratio`
class. Hence, print the given two ratios x & y, their sum (x + y), and their division (x / y).

Code:

#include<iostream.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 << "\n";
}

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(); cout << "\n";
}

You might also like