Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need to do object oriented programming for c++. I had to make make a program where it would add,subtract,multiply,and divide fraction. I got that

I need to do object oriented programming for c++. I had to make make a program where it would add,subtract,multiply,and divide fraction. I got that working, but it wont work for negative can anyone fix it and explain how they did it?

Source.cpp code:

#include "Fraction.h" #include using namespace std;

int main() { Fraction f1(-4, 6); Fraction f2(5, -9);

Fraction sum = sum.add(f1, f2); sum.print(sum); Fraction diff = diff.subtract(f1, f2); diff.print(diff); Fraction prod = prod.multiply(f1, f2); prod.print(prod); Fraction quot = quot.divide(f1, f2); quot.print(quot);

return 0; }

Header Class code:

#include using namespace std;

#pragma once #ifndef FRACTION_H #define FRACTION_H

class Fraction { private: int num; int den; public: Fraction(); Fraction(int, int); void setN(int); int getN(); void setD(int); int getD(); Fraction add(Fraction, Fraction); Fraction subtract(Fraction, Fraction); Fraction multiply(Fraction, Fraction); Fraction divide(Fraction, Fraction); Fraction simplify(Fraction); void print(Fraction); };

Fraction::Fraction() { setN(1); setD(1); }

Fraction::Fraction(int n, int d) { setN(n); setD(d); }

void Fraction::setN(int n) { num = (n > 0 ? n : 1); }

void Fraction::setD(int d) { den = (d > 0 ? d : 1); }

int Fraction::getN() { return num; }

int Fraction::getD() { return den; }

Fraction Fraction::add(Fraction f1, Fraction f2) { Fraction temp;

temp.num = f1.num * f2.den + f2.num * f1.den; temp.den = f1.den * f2.den;

return temp; }

Fraction Fraction::subtract(Fraction f1, Fraction f2) { Fraction temp;

temp.num = f1.num * f2.den - f2.num * f1.den; temp.den = f1.den * f2.den;

return temp; }

Fraction Fraction::multiply(Fraction f1, Fraction f2) { Fraction temp;

temp.num = f1.num * f2.num; temp.den = f1.den * f2.den;

return temp; }

Fraction Fraction::divide(Fraction f1, Fraction f2) { Fraction temp;

temp.num = f1.num * f2.den; temp.den = f1.den * f2.num;

return temp; }

Fraction Fraction::simplify(Fraction f1) { Fraction temp; for (int x = f1.den; x >= 1; x--) { if (f1.num % x == 0 && f1.den % x == 0) { temp.num = f1.num / x; temp.den = f1.den / x; break; } } return temp; }

void Fraction::print(Fraction f) { Fraction simp = simplify(f); cout << simp.num << "/" << simp.den << endl; }

#endif

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions