C++ adding fractions Main: FRACTION.CPP : FRACTION.H : input file contains: 30 /
ID: 664147 • Letter: C
Question
C++ adding fractions
Main:
FRACTION.CPP :
FRACTION.H :
input file contains:
30 / 70 + 4 / 5
10 / 30 - 2 / 7
20 / 10 * 5 / 3
40 / 90 / 1 / 9
4 / 5 = 4 / 5
4 / 4 = -1 / -1
2 / 3 = 3 / 2
Output should look like:
30/70 + 4/5 = 43/35
10/30 - 2/7 = 1/21
20/10 * 5/3 = 10/3
40/90 / 1/9 = 4/1
4/5 = 4/5 = True
4/4 = -1/-1 = True
2/3 = 3/2 = False
ALSO, need a default constructor to set numerator & denominator to zero
- input >> frac.numerator; // reads one integer out of the stream
#include #include #include #include "Fraction . h" iostream> using namespace std int mainO f // Input/output files ifstream fin("input.txt"); ofstream fout("output.txt"); // Throw error if can't open input file if(!fin) cerrExplanation / Answer
//Fraction.h
#include <iostream>
using namespace std;
class Fraction
{
//Add the variables and functions you need to. getGCD and reduce
//are provided for you
public:
int numerator,denominator;
private:
int getGCD(int num1,int num2);
public:
void reduce();
Fraction()
{
numerator=0;
denominator=0;
}
};
//Fraction cpp
#include "Fraction.h"
#include <iostream>
#include <string.h>
using namespace std;
int Fraction::getGCD(int num1,int num2)
{
int remainder=num2%num1;
if(remainder!=0)
return getGCD(remainder,num1);
return num1;
}
void Fraction::reduce()
{
int gcd=getGCD(numerator,denominator);
numerator/=gcd;
denominator/=gcd;
}
//main cpp
#include "Fraction.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin("input.txt");
ofstream fout("output.txt");
if(!fin)
{
cerr<<"Error opening input file";
//system("pause"");
}
while(fin.good())
{
Fraction fract1,fract2;
char oper;
fin>>fract1.numerator>>oper>>fract2.numerator;//calling class members via object
fout<<fract1.numerator<<" "<<oper<<" "<<fract2.numerator<<"="; //calling class members via object
switch(oper)
{
case '+':
fout<<fract1.numerator+fract2.numberator<<endl;
break;
case '-':
fout<<fract1.numberator-fract2.numerator<<endl;
break;
case '*':
fout<<fract1.numberator-fract2.numerator<<endl;
stdout<<fract1<<*fract<<<<endl;
break;
case '/':
fout<<fract1/fract2<<endl;
break;
case '=':
if(fract1==fract2)
fout<<"True"<<endl;
else
fout<<"False"<<endl;
break;
}
}
fin.close();
fout.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.