Question

In: Computer Science

I am writing a program that will work with two other files to add or subtract...

I am writing a program that will work with two other files to add or subtract fractions for as many fractions that user inputs. I need to overload the + and - and << and >> opperators for the assignment. The two files posted cannot be modified. Can someone correct the Fraction.ccp and Frction.h file that I am working on? I'm really close.

//
// useFraction.cpp
//
// DO NOT MODIFY THIS FILE
//

#include "Fraction.h"
#include<iostream>
using namespace std;

void print_fraction(const Fraction& f)
{
  cout << "print_fraction: " << f.getNum() << "/" << f.getDen() << endl;
}

int main()
{
  Fraction x(2,3);
  Fraction y(6,-2);

  cout << x << endl;
  cout << y << endl;

  cin >> y;
  cout << y << endl;
  print_fraction(y);
  Fraction z = x + y;
  cout << x << " + " << y << " = " << z << endl;
}
//
// calculator.cpp
//
// DO NOT MODIFY THIS FILE
//

#include "Fraction.h"
#include<iostream>
#include<stdexcept>
using namespace std;

int main()
{
  Fraction x,y;
  char op;
  try
  {
    cin >> x;
    cin >> op;
    while ( cin && ( op == '+' || op == '-' ) )
    {
      cin >> y;
      if ( op == '+' )
        x = x + y;
      else
        x = x - y;
      cin >> op;
    }
    cout << x << endl;
  }
  catch ( invalid_argument& e )
  {
    cout << "Error: " << e.what() << endl;
  }
}

//MYFILES


//fraction.cpp
Fraction::Fraction()
{
num = 0;
dem = 1;
}
Fraction::Fraction(int a, int b){
num = a;
dem = b;
}
int Fraction::getNum(){
return num;
}
int Fraction::getDen(){
return den;
}
void Fraction::setNum(int a)
{
num = a;
}
void Fraction::setDen(int b)
{
den = b;
}
Fraction Fraction ::operator+( const Fraction & rightFraction )
{
Fraction temp;
temp.num = ( num * rightFraction.den ) + ( den * rightFraction.num );
temp.den = den * rightFraction.den;
return temp;
} // end function operator+
Fraction Fraction ::operator-( const Fraction & rightFraction )
{
Fraction temp;
temp.num = ( num * rightFraction.den ) - ( den * rightFraction.num );
temp.den = den * rightFraction.den;
return temp;
} // end function operator-
ostream& operator<<(ostream& os, const Fraction& f)
{
os << f.getNum() << "/" << f.getDen(); // output in fraction format
return os;
}
istream& operator>>(istream& is, Fraction& f)
{
int t, b;
do
{
// Read the numerator first
is >> t;
char c;
is >> c;
if (c == '/') // If there is a slash, then read the next number
is >> b;
else //otherwise just "unget()" it and set to b=1
{
is.unget();
b = 1;
}
if (b==0) // if b came out to 0, fraction is not possible, so we loop back to ask user input again
throw "Error: divide by zero ";
} while(b==0);
f = Fraction(t, b); // set the fraction
return is;
}
//Header file

#indef

#def

class Fraction{
public:
Fraction();
Fraction(int, int);
getNum();
getDen();
setNum(int);
setDen(int);
friend operator-( const Fraction & rightFraction );
friend operator+( const Fraction & rightFraction );
friend ostream& operator<<(ostream& os, const Fraction& f);
friend istream& operator>>(istream& is, Fraction& f);

private:
int num;
int den;
};

Solutions

Expert Solution

calculator.cpp

//
// calculator.cpp
//
#include "Fraction.h"
#include<iostream>
#include<stdexcept>
using namespace std;

int main()
{
Fraction x,y;
char op;
try
{
    cin >> x;
    cin >> op;
    while ( cin && ( op == '+' || op == '-' ) )
    {
      cin >> y;
      if ( op == '+' )
        x = x + y;
      else
        x = x - y;
      cin >> op;
    }
    cout << x << endl;
}
catch ( invalid_argument& e )
{
    cout << "Error: " << e.what() << endl;
}
}

Fraction.h

#ifndef Fraction_h
#define Fraction_h
#include <iostream>
using namespace std;
class Fraction
{
public:
//Functions
Fraction();
Fraction(int,int);
   int getNum() const;
   int getDem() const;
   void setNum(int num);
   void setDem(int den);
   void reduce();
   void signs();
   friend   ostream& operator<<(ostream &out,const Fraction &);
   friend   istream& operator>>(istream &,Fraction &);
   Fraction operator+(const Fraction );
   Fraction operator-(const Fraction );
   Fraction& operator=(const Fraction );
private:
int nemer;
int denom;
};
#endif

Fraction.cpp

#include "Fraction.h"
#include <stdexcept>
#include <iostream>
#include <cstdlib>
using namespace std;
Fraction::Fraction()
{
   setNum(0);
   setDem(0);
}
Fraction::Fraction(int nem, int dem)
{
   if (dem == 0)
   {
       throw invalid_argument("division by zero");
   }
   else
   {
       setNum(nem);
       setDem(dem);
       reduce();
   }
  
}
void Fraction::setNum(int num)
{
   nemer = num;
}
void Fraction::setDem(int den)
{
   denom = den;
}
int Fraction::getNum() const
{
   return nemer;
}
int Fraction::getDem() const
{
  
   return denom;
}
void Fraction::reduce()
{
   signs();
   int Sign = 1;
   int nem = getNum();
   int den = getDem();
   if (nem < 0)
   {
       nem *= -1;
       Sign = -1;
   }
   for (int i = (nem * den); i > 1; i--)
   {
       if ((nem % i == 0) && (den % i == 0))
       {
           nem /= i;
           den /= i;
       }
   }
   nem *= Sign;
   setNum(nem);
   setDem(den);
}
void Fraction::signs()
{
   int nem = getNum();
   int den = getDem();
   if (den < 0)
   {
       nem *= -1;
       den *= -1;
   }
   setNum(nem);
   setDem(den);
}
Fraction &Fraction::operator=(const Fraction frac)
{
   int num = frac.getNum();
   int den = frac.getDem();
   (*this).setNum(num);
   (*this).setDem(den);
   return *this;
}
istream &operator>>(istream &in, Fraction &frac)
{
   char Dum;
   int num;
   int den;
   in >> num;
   in >> Dum;
   in >> den;
   if (den == 0)
   {
       throw invalid_argument("Error: division by zero");
       exit(0);
   }
   frac.setNum(num);
   frac.setDem(den);
   frac.reduce();
   return in;
}
ostream &operator<<(ostream& out, const Fraction& frac)
{
;
   if (frac.getDem() == 1)
       out << frac.getNum();
   else
   {
       out << frac.getNum() << '/' << frac.getDem();
      
   }
   return out;
}
Fraction Fraction::operator+(const Fraction frac)
{
   int Nsum = ((*this).getNum() * frac.getDem()) + (getNum() * (*this).getDem());
   int Dsum = ((*this).getDem() * frac.getDem());
   Fraction frac2(Nsum, Dsum);
   frac2.reduce();
   return frac2;
}
Fraction Fraction::operator-(const Fraction frac)
{
   int Nsum= ((*this).getNum() * frac.getDem()) - (getNum() * (*this).getDem());
   int Dsum = ((*this).getDem() * frac.getDem());
   Fraction frac2(Nsum, Dsum );
   frac2.reduce();
   return frac2;
}

useFraction.cpp

//
// useFraction.cpp
//

#include "Fraction.h"
#include<iostream>
using namespace std;

int main()
{
Fraction x(2,3);
Fraction y(6,-2);

cout << x << endl;
cout << y << endl;

cin >> y;
cout << y << endl;
Fraction z = x + y;
cout << x << " + " << y << " = " << z << endl;
}



Related Solutions

I am Writing a C-Program to read and write files. but none of my code is...
I am Writing a C-Program to read and write files. but none of my code is working like it should be. Please fix all code and supply output response. Please try to use existing code and code in comments. But if needed change any code that needs to be changed. Thank you in advance //agelink.c //maintains list of agents //uses linked list #include <stdio.h> #include <stdlib.h> #define TRUE 1 void listall(void); void newname(void); void rfile(void); void wfile(void); struct personnel {...
I am writing a shell program in C++, to run this program I would run it...
I am writing a shell program in C++, to run this program I would run it in terminal like the following: ./a.out "command1" "command2" using the execv function how to execute command 1 and 2 if they are stored in argv[1] and argv[2] of the main function?
I am trying to add two linked-list based integers, but the program keeps giving me the...
I am trying to add two linked-list based integers, but the program keeps giving me the incorrect result. I am trying to add (List 1: 43135) + (List 2: 172). I have pasted the code below #include <iostream> using namespace std; //Linked list node class Node {    public:    int num;    Node* next; }; //Function to create a new node with given numbers Node *new_Node(int num) {    Node *newNode = new Node();    newNode->num = num;   ...
Hello, I am writing the initial algorithm and refined algorithm for a program. I just need...
Hello, I am writing the initial algorithm and refined algorithm for a program. I just need to make sure I did it correctly. I'm not sure if my formula is correct. I appreciate any help, thank you! TASK: Write a program that will calculate the final balance in an investment account. The user will supply the initial deposit, the annual interest rate, and the number of years invested. Solution Description: Write a program that calculates the final balance in an...
I am writing a matlab program where I created a figure that has a few different...
I am writing a matlab program where I created a figure that has a few different elements to it and now I need to move that figure into a specific excel file into a specific set of boxes in the excel file. With numbers and text I have always used the xlswrite function for this in order to put data into specific boxes. How do I do the same with this figure? The figure I have is called like this:...
Write a calculator program that prompts the user with the following menu: Add Subtract Multiply Divide...
Write a calculator program that prompts the user with the following menu: Add Subtract Multiply Divide Power Root Modulus Upon receiving the user's selection, prompt the user for two numeric values and print the corresponding solution based on the user's menu selection. Ask the user if they would like to use the calculator again. If yes, display the calculator menu. otherwise exit the program. EXAMPLE PROGRAM EXECUTION: Add Subtract Multiply Divide Power Root Modulus Please enter the number of the...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
I am writing a paper on the dealiest epidemics in recorded history. I am looking for...
I am writing a paper on the dealiest epidemics in recorded history. I am looking for information on the polio virus, thypoid fever, and the black palgue. I need help identifying when these diseases started, what started them, the virus or mutation that caused them, how they spread and the preventative measures to stop them.
I am writing a paper on the dealiest epidemics in recorded history. I am looking for...
I am writing a paper on the dealiest epidemics in recorded history. I am looking for information on typhus epidemic/camp fever. I need help identifying when these diseases started, what started them, the virus or mutation that caused them, how they spread and the preventative measures to stop them.
I am writing a paper on Financial Restructuring. I am required to pick a company that...
I am writing a paper on Financial Restructuring. I am required to pick a company that is in [potential] trouble of defaulting/bankruptcy. I have chosen Toys R Us. I am required to: 1) Analyze the company's (Toys R Us) financial history and current financial situation. 2) Propose a financial restructuring proposal. It is my understanding that I need to look at all possible financial statements, income statements, cash flows, and use financial tools to "financially restructure" and propose a "fix"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT