Write a program in C++ with a ratio class using member functions like assign() function to initialize its member data integer numerator and denominator, convert() function to convert the ratio into double, invert() function to get the inverse of the ratio and print() function to print the ratio and its reciprocal.
12th CS Part-1 Practical Solutions of experiment number 3. The contents in this website is completely follow the pattern Of Maharashtra Board.
#include <iostream.h>
#include <conio.h>
class Ratio {
private:
int numerator;
int denominator;
public:
// Assigns the values num and den to the numerator and denominator, respectively
void assign(int num, int den) {
numerator = num;
denominator = den;
}
// Returns the ratio as a double
double convert() {
return (double)numerator / denominator;
}
// Inverts the ratio
void invert() {
int temp = numerator;
numerator = denominator;
denominator = temp;
}
// Prints the ratio and its reciprocal
void print() {
cout << "Ratio: " << numerator << "/" << denominator << endl;
cout << "Reciprocal: " << denominator << "/" << numerator << endl;
}
};
void main() {
Ratio x; // Creates an object of the Ratio class
x.assign(22, 7); // Calls the assign function to assign the values 22 and 7 to the numerator and denominator, respectively
x.print(); // Calls the print function to print the ratio and its reciprocal
cout << "Ratio as double: " << x.convert() << endl; // Calls the convert function to print the ratio as a double
x.invert(); // Calls the invert function to invert the ratio
x.print(); // Calls the print function to print the inverted ratio and its reciprocal
getch(); // Holds the output screen until a key is pressed
}