Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2. Define a class for rational numbers. A rational number is a number that can b

ID: 3567057 • Letter: 2

Question

2. Define a class for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, 1/2, 3/4, 64/2, and so forth are all rational numbers. (By 1/2 and so on we mean the everyday fraction, not the integer division this expression would produce in a C++ program.) Represent rational numbers as two values of type int, one for the numerator and one for the denominator. Call the class Rational. Include a constructor with two arguments that can be used to set the member variables of an object to any legitimate values. Also include a constructor that has only a single parameter of type int; call this single parameter wholeNumber and define the constructor so that the object will be initialized to the rational number wholeNurnber/1. Include a default constructor that initializes an object to 0 (that is, to 0/1). Overload the input and output operators > > and

Explanation / Answer

#include #include using namespace std; class Rational { public: Rational(); // Initializes the rational number to 0 Rational (int wholeNumber); // Initializes the rational number to wholeNumber/1 Rational (int m, int n); // Initializes the rational number to m/n if n is not 0; // the sign of the rational is stored in the numerator // (the denominator is always positive); // exits if n = 0 (invalid rational number) friend ostream& operator (istream& ins, Rational& r); // Precondition: If ins is a file input stream, then ins has // already been connected to a file. The rational number in // the input stream is in the form of an integer followed by // the slash character followed by an integer. // Postcondition: r has been set to the input value (and // standardized so the denominator is positive). private: int num; // the numerator of the number int denom; // the denominator of the number void standardize(); // Precondition: num and denom have values // Postcondition: if denom is 0 the program is terminated; // otherwise the rational number is standardized so that // denom is positive. }; // ===================== // main function // ===================== int main () { // // Variable declarations // char doAgain; // for the loop control int m, n; // numerator and denominator - m/n Rational r; do { // // Read in a rational number // cout > r; cout
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote