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.
#include<iostream.h> // include input/output stream library
#include<conio.h> // include console input/output library
class ratio // define a class named "ratio"
{
private: // define the private data members of the class
int num, den; // numerator and denominator of the ratio
float f, ref; // float values for the ratio and its reciprocal
double n; // double value for the converted ratio
public: // define the public member functions of the class
void assign(); // function to assign values to the numerator and denominator
void convert(); // function to convert the ratio to double
void invert(); // function to calculate the reciprocal of the ratio
void print(); // function to print the ratio and its reciprocal
};
void ratio::assign() // definition of the assign member function
{
cout << " Enter the numerator of the ratio\n"; // prompt the user to enter the numerator
cin >> num; // read in the numerator
cout << " Enter the denominator of the ratio\n"; // prompt the user to enter the denominator
cin >> den; // read in the denominator
f = (float)num / den; // calculate the ratio as a float
}
void ratio::convert() // definition of the convert member function
{
n = f; // convert the ratio to a double
}
void ratio::invert() // definition of the invert member function
{
ref = 1 / f; // calculate the reciprocal of the ratio
}
void ratio::print() // definition of the print member function
{
cout << "\n The original ratio is=\n" << f; // print the original ratio
cout << "\n The reciprocal of the ratio is=\n" << ref; // print the reciprocal of the ratio
}
void main() // main function
{
clrscr(); // clear the console screen
ratio obj; // create an object of the ratio class
obj.assign(); // call the assign member function to assign values to the object
obj.convert(); // call the convert member function to convert the ratio
obj.invert(); // call the invert member function to calculate the reciprocal of the ratio
obj.print(); // call the print member function to print the ratio and its reciprocal
getch(); // wait for user input before exiting the program
}