In: Computer Science
First lab: Create a Fraction class
Modify the Fraction class created in the first lab above as follows. Read the entire description before writing any code
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
main.cpp
#include<iostream>
#include<iomanip>
using namespace std;
class Fraction
{
private:
int numerator, denominator;
public:
Fraction()
{
numerator = 0;
denominator = 1;
}
Fraction(int a, int b)
{
numerator = a;
denominator = b;
if(denominator==0){
cout<<"Error!!! Denominator cannot be zero. Setting it to
1\n";
denominator =
1;
}
}
Fraction(int whole,int a, int b)
{
numerator = whole*b;
numerator += a;
denominator = b;
if(denominator==0){
cout<<"Error!!! Denominator cannot be zero. Setting it to
1\n";
denominator =
1;
}
}
void set(int a, int b)
{
numerator = a;
denominator = b;
if(denominator==0){
cout<<"Error!!! Denominator cannot be zero. Setting it to
1\n";
denominator =
1;
}
}
void set(int whole,int a, int b)
{
numerator = whole*b;
numerator += a;
denominator = b;
if(denominator==0){
cout<<"Error!!! Denominator cannot be zero. Setting it to
1\n";
denominator =
1;
}
}
void setNumerator(int n){
numerator = n;
}
void setDenominator(int d){
denominator = d;
if(denominator==0){
cout<<"Error!!! Denominator cannot be zero. Setting it to
1\n";
denominator =
1;
}
}
int getNumerator(){
return numerator;
}
int getDenominator(){
return denominator;
}
string toString(){
int whole =
numerator/denominator;
int num =
numerator%denominator;
string res="";
if(whole!=0){
res=to_string(whole)+"
"+to_string(num)+"/"+to_string(denominator);
}else{
res=to_string(num)+"/"+to_string(denominator);
}
return res;
}
};
int main()
{
Fraction f(11,4);
cout<<f.toString()<<endl;
f.set(11,0);
cout<<f.toString()<<endl;
f.set(5,11,12);
cout<<f.toString()<<endl;
cout<<"Numerator :
"<<f.getNumerator()<<endl;
cout<<"DeNominator :
"<<f.getDenominator()<<endl;
return 0;
}
output