Hello everyone,
I'm creating a program that it is suppose to add, subtract, multiply and also divide fractions and after that, the result has to be reduced to the lowest terms.
However, I'm not sure how the algorithm of reducing fractions works.
Here is part of my code:
Thanks for all the support,
Doug
I'm creating a program that it is suppose to add, subtract, multiply and also divide fractions and after that, the result has to be reduced to the lowest terms.
However, I'm not sure how the algorithm of reducing fractions works.
Here is part of my code:
Code:
//Header File
#include <iostream>
using namespace std;
class fraction
{
private:
int numerator;
int denominator;
public:
fraction() : numerator(0), denominator(0) //Constructor (no args)
{ }
fraction(int num, int den=1); //(Fraction F2) : numerator(num), denominator(den) //Constructor (two args)
friend fraction operator +(fraction f1, fraction f2);
friend fraction operator-(fraction f1, fraction f2);
friend fraction operator*(fraction f1, fraction f2);
friend fraction operator/(fraction f1, fraction f2);
friend istream& operator >> (istream& s, fraction& e);
friend ostream& operator<< (ostream& out, fraction& f);
};
//fraction.cpp
#include <iostream>
#include <string>
#include "fraction.h"
using namespace std;
fraction operator+(fraction f1, fraction f2)
{
fraction temp;
temp.numerator = f1.numerator * f2.denominator + f1.denominator * f2.numerator;
temp.denominator = f1.denominator * f2.denominator;
return temp;
}
ostream& operator<<(ostream& out, fraction& f)
{
out << f.numerator << "/" << f.denominator;
return out;
}
istream& operator >> (istream& s, fraction& f)
{
cout << "\nPlease type the numerator: ";
cin >> f.numerator;
cout << "Please type the denominator: ";
cin >> f.denominator;
return s;
}
//calc.cpp
#include <iostream>
#include <string>
#include "fraction.h"
using namespace std;
int main()
{
fraction f1;
fraction f2;
fraction answer;
fraction f3;
char symbol = ' ';
string nome;
while (true)
{
cout << "A\tADD\n";
cout << "S\tSUBTRACT\n";
cout << "M\tMULTIPLY\n";
cout << "D\tDIVIDE\n";
cout << "E\tEXIT\n";
cout << "\nWhat operation do you want to use? ";
cin >> symbol;
if (symbol == 'e' || symbol == 'E')
exit(0);
switch (symbol)
{
case 'A':
cout << "\nPlease type values for fraction 1 and fraction 2\n";
cin >> f1 >> f2;
cout << "\nFraction 1 = " << f1 << "\nFraction 2 = " << f2;
f3 = f1 + f2;
cout << "\n\bThe sum of F1 and F2 is: " << f3 << "\n" << endl;
break;
}
return 0;
}
Doug
Comment