1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
|
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
class Frac
{
public:
Frac(int = 1, int = 1);
void reduce(Frac &);
void add(Frac &, Frac &);
void subtract(Frac &, Frac &);
void multiply(Frac &, Frac &);
void divide(Frac &, Frac &);
void printOut();
void reciprocal();
private:
int num, den;
};
Frac::Frac(int a, int b)
{
num = a;
den = b;
int c, d, gcd, r;
c = num;
d = den;
r = a % b;
while (r != 0)
{
c = d;
c = r;
r = c % d;
}
gcd = d;
num = num / gcd;
den = den / gcd;
}
void Frac::reduce(Frac &c)
{
int a, b, gcd, r;
a = c.num;
b = c.den;
r = a % b;
while (r != 0)
{
a = b;
b = r;
r = a % b;
}
gcd = b;
c.num = c.num / gcd;
c.den = c.den / gcd;
//cout << num << "/" << den << endl;
}
void Frac::add(Frac &c , Frac &sum)
{
sum.den = den * c.den;
sum.num = (num * (sum.den / den)) + (c.num * (sum.den / c.den));
reduce(sum);
}
void Frac::subtract(Frac &c, Frac &sub)
{
sub.den = den * c.den;
sub.num = (num * (sub.den / den)) - (c.num * (sub.den / c.den));
reduce(sub);
}
void Frac::multiply(Frac &c, Frac &mul)
{
mul.num = num * c.num;
mul.den = den * c.den;
reduce(mul);
}
void Frac::divide(Frac &c, Frac &div)
{
div.num = num * c.den;
div.den = den * c.num;
reduce(div);
}
void Frac::printOut()
{
cout << num << "/" << den <<" ";
}
void Frac::reciprocal()
{
int a;
a = den;
den = num;
num = a;
}
int main()
{
Frac a(40, 50), b(36, 72), sum(4, 4), subt(4, 4), mult(4, 4), div(4, 4);
a.add(b, sum);
cout << "The sum of ";
a.printOut();
cout << "& ";
b.printOut();
cout << " is: ";
sum.printOut();
cout << endl << endl;
a.subtract(b, subt);
cout << "The deduction of ";
a.printOut();
cout << "& ";
b.printOut();
cout << " is: ";
subt.printOut();
cout << endl << endl;
a.multiply(b, mult);
cout << "The product of ";
a.printOut();
cout << "& ";
b.printOut();
cout << " is: ";
mult.printOut();
cout << endl << endl;
a.divide(b, div);
cout << "The quotient of ";
a.printOut();
cout << "& ";
b.printOut();
cout << " is: ";
div.printOut();
cout << endl << endl;
//a.subtract(num2, den2, subnum, subden);
cout << "The reciprocal of ";
a.printOut();
cout << "& ";
b.printOut();
cout << " is: ";
a.reciprocal();
b.reciprocal();
a.printOut();
cout << " & ";
b.printOut();
cout << endl << endl;
system("PAUSE");
return 0;
}
| |