Question
Write a C++ class to implement rational numbers as specified below. Here is the h File Rat.h: Note: you may not modify the Rat.h in
Write a C++ class to implement rational numbers as specified below. Here is the h File Rat.h:
Note: you may not modify the Rat.h in anyway and you should produce output exactly like the sample run below.
class details | |
Rat.h | class Rat { public: Rat(); // constructs 0/1 Rat(int n_, int d_); // exits prog. with error message if d_==0 int getN() const; // getters int getD() const; void setN(int n_); // setters void setD(int d_); // exits prog. with error message if d_==0 Rat norm() const; // returns normalized number Rat reduce() const; // reduces number to lowest terms int cmp(Rat &r) const; // returns -1,0, or 1 Rat add(Rat& op2) const; // adds 2 numbers Rat sub(Rat& op2) const; // subtracts op2 from op1 friend std::ostream& operator |
sample driver | #include int main() { Rat r1(2,4), r2(8,-16), r3(0,-4); cout |
Legal rational numbers are to be stored exactly as they are created (i.e. they need not be stored reduced or in normal form). In normal form denominators are always positive and the value 0 has no sign and is always normalized to 0/1 (i.e. 9/-3 normalized would be -9/3, 0/-3 would be 0/1). The reduce function reduces all values equal to 0 to 0/1. The arithmetic operators add and subalways return a number reduced and in normal form. The function cmp compares two rational numbers op1.cmp(op2) returning -1 if op1
Sample Driver Output:
Terminaltcsh-42x10 macbook:~/C++/% macbook:~/ C++/% 2/4 8/-16 0/-4 g++ ratDriver.cpp a. out Rat.cpp 1 macbook: ~/C++/%
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started