In C++ Rational Arithmetic I A rational number is a quotient of two integers. Fo
ID: 3914168 • Letter: I
Question
In C++
Rational Arithmetic I
A rational number is a quotient of two integers. For example, 12/5, 12/–4, –3/4, and 4/6 are all rational numbers. A rational number is said to be in reduced form if its denominator is positive and its numerator and denominator have no common divisor other than 1. For example, the reduced forms of the rational numbers given above are 12/5, –3/1, –3/4, and 2/3.
Write a class called Rational with a constructor Rational(int, int) that takes two integers, a numerator and a denominator, and stores those two values in reduced form in corresponding private members. The class should have a private member function void reduce() that is used to accomplish the transformation to reduced form. The class should have an overloaded insertion operator << that will be used for output of objects of the class.
Explanation / Answer
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks
//Code
#include<iostream>
using namespace std;
class Rational{
int numerator;
int denominator;
//private method to reduce the rational number into lowest form
void reduce(){
/**
* Finding the GCD
*/
int GCD = gcd(numerator, denominator);
/**
* removing the GCD from numer..and denom..
*/
numerator = numerator / GCD;
denominator = denominator / GCD;
}
/**
* A private method to calculate the greatest common divisor of two numbers
*/
int gcd(int x, int y) {
//removing sign
x= x>=0? x: -x;
y= y>=0? y: -y;
if (x % y == 0)
return y;
return gcd(y, x % y);
}
public:
//constructor
Rational(int n, int d){
//initializing numerator and denominator
numerator=n;
denominator=d;
if(denominator==0){
denominator=1;//preventing dinominator being 0
}
//reducing to simplest form
reduce();
}
//getter for numerator
int getNumerator() const{
return numerator;
}
//getter for dinominator
int getDenominator() const{
return denominator;
}
};
//overloaded << operator for displaying rational number in a/b form
ostream & operator << (ostream &out, const Rational &r)
{
out<<r.getNumerator()<<"/"<<r.getDenominator();
}
int main(){
//Testing the Rational class
Rational r1(10,5); //should be reduced to 2/1
cout<<r1<<endl;
Rational r2(11,7); //already in reduced state 11/7
cout<<r2<<endl;
return 0;
}
/*OUTPUT*/
2/1
11/7