Create a class RationalNumber (fractions) with the following functionality:
● Has a constructor that prevents a 0 denominator in a fraction and calls the reduce function to simplify the fraction
● Has a default constructor
● Has a private member function that reduces a fraction (see below)
● Has accessor and mutator functions for both numerator and denominator
● Has a function that displays the fraction in appropriate format. For example, the fraction 3/1 should be displayed as 3 and 7/2 as 3 1/2
This class should be implemented in two files, a header (.h) file and a source (.cpp) file. There should be a third file that contains a main function. In the main function, create and display at least three fractions including one that is reduced by the constructor, one with a denominator of 1 and one with a numerator greater than the denominator.
I have done everything, yet it doesnt want to run. anyone care to look it over
rational.cpp
#include <iostream>
#include "rational.h"
using namespace std;
int main()
{
cout << "Fraction 1 = ";
RationalNum rn(3,1);
cout << "Fraction 2 = ";
RationalNum rn1(2,6);
cout << "Fraction 3 = ";
RationalNum rn2(7,2);
return 0;
}
RationalNum:: RationalNum()
{
Numerator = 0;
Denominator = 0;
cout << 0;
}
RationalNum::RationalNum(int n, int d)
{
Numerator = n;
Denominator = d;
if(d==0)
cout << "Entry is Invalid" << endl;
else
reduce();
}
void RationalNum::setNumerator(int n)
{
Numerator = n;
}
void RationalNum::setDenominator(int d)
{
Denominator = d;
}
int RationalNum::getDenominator()
{
return Denominator;
}
int RationalNum::getNumerator()
{
return Numerator;
}
//Function to redure the fraction
void RationalNum::reduce()
{
int Largest, GCD = 1; // Greatest Common Divisor
Largest = (Numerator > Denominator) ? Numerator: Denominator;
for(int loop = 2; loop <=Largest; loop++)
if(Numerator % loop == 0 && Denominator % loop == 0)
GCD = loop;
Numerator /= GCD;
Denominator /= GCD;
display();
}
void RationalNum::display()
{
if(Denominator == 1)
cout << Numerator << endl;
else if(Numerator < Denominator)
cout << Numerator << "/" << Denominator << endl;
else
{
double Whole = (double) Numerator/Denominator;
int Mixed = Whole;
Whole = Whole - Mixed;
Whole*=20;
cout << Mixed << " ";
RationalNum(10,20);
}
}
rationaltester.cpp
#include <iostream>
#include "rational.h"
using namespace std;
int main()
{
RationalNum rn(7,3);
return 0;
}
rational.h
#ifndef RATIONALNUM_H
#define RATIONANUM_H
class RationalNum
{
private:
int Numerator;
int Denominator;
void reduce();
public:
RationalNum();
RationalNum(int, int);
void setNumerator(int);
void setDenominator(int);
void display();
int getNumerator();
int getDenominator();
};
#endif

New Topic/Question
Reply




MultiQuote




|