Napisz program w C++-->Dodawanie ułamków ze skracaniem. Prosze o szybką odpowiedź daje nam wszystko co chcecie.​



Odpowiedź :

plik *.h nie chce się dodać jako załącznik, więc wklejam wszystko tutaj:

// main.cpp

#include <iostream>

#include "frac.h"

int main(int argc, char** argv)

{

frac frac1, frac2;

std::cin >> frac1 >> frac2;

std::cout << frac1 + frac2 << std::endl;

system("pause");

return 0;

}

//--------------------

// frac.h

#pragma once

#include <iostream>

class frac

{

int nominator;

int denominator;

void normalise();

int lcm(int, int);

int gcd(int, int);

public:

frac();

frac(int, int);

friend std::ostream& operator<<(std::ostream&, const frac&);

friend std::istream& operator>> (std::istream&, frac&);

frac operator+(frac const&);

};

//--------------------

//frac.cpp

#include "frac.h"

using namespace std;

void frac::normalise()

{

int div = gcd(nominator, denominator);

nominator /= div;

denominator /= div;

}

int frac::lcm(int a, int b)

{

return (abs(a) / gcd(a, b)) * abs(b);

}

int frac::gcd(int a, int b)

{

int t;

while (0 != b)

{

 t = b;

 b = a % b;

 a = t;

}

return a;

}

frac::frac() : nominator(0), denominator(1)

{}

frac::frac(int nominator, int denominator)

{

if (0 == denominator)

 throw new invalid_argument("denominator must be non zero");

this->nominator = nominator;

this->denominator = denominator;

normalise();

}

ostream& operator<<(ostream& out, const frac& fr)

{

out << fr.nominator;

if (1 != fr.denominator) out << '/' << fr.denominator;

return out;

}

istream& operator>> (istream& in, frac& fr)

{

int n, d;

in >> n >> d;

if (0 == d)

 throw new invalid_argument("denominator must be non zero");

fr.nominator = n;

fr.denominator = d;

fr.normalise();

return in;

}

frac frac::operator+(frac const& fr)

{

frac sum;

int l = lcm(denominator, fr.denominator);

int mlt1 = l / denominator;

int mlt2 = l / fr.denominator;

sum.denominator = l;

sum.nominator = nominator * mlt1 + fr.nominator * mlt2;

sum.normalise();

return sum;

}