Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // наследование.cpp: определяет точку входа для консольного приложения.
- //
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- class Rational {
- private:
- int chis, znam;
- public:
- Rational() {
- chis = 0; znam = 1;
- }
- Rational(int x) {
- chis = x; znam = 1;
- }
- Rational(int c, int z) {
- chis = c; znam = z;
- }
- Rational(const char *str) {
- chis = 0;
- znam = 1;
- sscanf(str, "%d / %d", &chis, &znam);
- }
- int get_chis() const {
- return chis;
- }
- int get_znam() const {
- return znam;
- }
- double approx() {
- return get_chis()/double(get_znam());
- }
- friend double approx(Rational r);
- };
- class MegaRational: public Rational {
- public:
- MegaRational(): Rational()
- {
- }
- MegaRational(int x): Rational(x)
- {
- }
- MegaRational(int c, int z): Rational(c, z)
- {
- }
- MegaRational(const char *str) : Rational(str)
- {
- }
- void drob(Rational a) {
- if(a.get_chis() > a.get_znam()) {
- cout << "B = " << a.get_chis() / a.get_znam() << " и " << a.get_chis()/double(a.get_znam()) <<endl;
- }
- else
- cout << "C = " << a.get_chis() % a.get_znam()<< endl;
- }
- };
- double approx(Rational r) {
- return r.chis/double(r.znam);
- }
- Rational operator+(Rational a, Rational b) {
- Rational res(a.get_chis()*b.get_znam() + a.get_znam()*b.get_chis(),
- a.get_znam()*b.get_znam());
- return res;
- }
- Rational operator-(Rational a, Rational b) {
- Rational res(a.get_chis() * b.get_znam() - b.get_chis() * a.get_znam(),
- a.get_znam() * b.get_znam());
- return res;
- }
- Rational operator*(Rational a, Rational b) {
- Rational res(a.get_chis() * b.get_chis(),
- a.get_znam() * b.get_znam());
- return res;
- }
- Rational operator/(Rational a, Rational b) {
- Rational res(a.get_chis() * b.get_znam(),
- a.get_znam() * b.get_chis());
- return res;
- }
- ostream& operator<<(ostream& o, Rational r) {
- o << r.get_chis() << " / " << r.get_znam();
- return o;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- Rational r1(1, 5),
- r2(4, 8),
- r3(4);
- MegaRational r4(3, 2),
- r5("2/7");
- Rational a = operator+(r1, r2);
- Rational b = operator-(r1, r5);
- Rational c = operator*(r2, r3);
- Rational d = operator/(r5, r2);
- cout << " r1 = " << r1 << endl;
- cout << " r2 = " << r2 << endl;
- cout << " r3 = " << r3 << endl;
- cout << " r4 = " << r4 << endl;
- cout << " r5 = " << r5 << endl;
- cout << endl;
- Rational res = r1 + r2;
- cout << " a = " << a.approx() << " = " << res << endl;
- cout << " b = " << b.approx() << " = " << r1 - r5 << endl;
- cout << " c = " << c.approx() << " = " << r2 * r3 << endl;
- cout << " d = " << d.approx() << " = " << r5 / r2 << endl;
- cout << endl;
- cout << " r4 = " << r4.drob() << " = " << r4 << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement