ok i'm adding some more to it, plus the instructions:
Write a class Fraction to represent fractions such as 2/3, 5/4. or -3/7.
The class will have two constructors
Fraction(); //set numerator and denominator to 1)
Fraction(int numerator, int denominator);
The second constructor
will reduce the fraction if needed. Section 4.2 has an algorithm for finding the greatest common divisor of two numbers. Use it to write a function GCD;
if the denominator is negative, the constructor will make it positive and make the numerator negative.
the denominator of a fraction should not be 0. If the user passes a 0 denominator, the proper thing to do would be throw an exception, but we have not studied exception handling yet. So for now, we will assume a well-behaved use who will never pass a denominator of 0 to the constructor
Then overload the multiplication and division operators. Addition and subtraction are more complicated and we will leave that for another day
Also implement
int GCD(int a, int b); returns the greatest common divisor of a and b
void reduce(); reduces this fraction to lowest terms
string fractionToString(); returns a string of the form "3/4" if the numerator was 3 and the denominator was 4.
In the main function, create some fractions, multiply and divide them and print the result.
Implement the program as three files - a fraction.h header file, the main.cpp file and a fraction.cpp file. If you have trouble getting three files to work, try writing all in one file so you know the functions work and then separating it into the different files.
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
|
#include <iostream>
#include <string>
using namespace std;
class Fraction{
public:
Fraction();
Fraction(int numerator, int denominator);
string fractionToString();
int GCD(int a, int b);
private:
int numerator;
int denominator;
int a;
int b;
void reduce();
};
int main(int argc, const char * argv[])
{
Fraction f1(3,7);
Fraction f2(4,8);
Fraction product;
Fraction quotient;
product = f1*f2;
quotient = f1 / f2;
string s = product.fractionToString();
cout << s << endl;
cin.get();
return 0;
}
Fraction::Fraction()
{
this->numerator = 0;
this->denominator = 0;
}
Fraction::Fraction(int a, int b)
{
this->numerator = a;
this->denominator = b;
}
void Fraction::reduce()
{
int a, b, r;
a = (numerator);
b = (denominator);
if (a == 0)
{
numerator = 0;
denominator = 1;
return;
}
while (a != 0)
if (a<b)
{
r = a; a = b; b = r;
a = a - b;
}
int gcd = b;
numerator = numerator / gcd;
denominator = denominator / gcd;
}
int Fraction::GCD(int a, int b)
{
while (a != b){
if (b > a){
b = b - a;
}
else { a = a - b; }
}
return a, b;
}
string Fraction::fractionToString()
{
return to_string(numerator) + "/" + to_string(denominator);
}
|