I have homework that I've been procrastinating. Here's the problem:
"Create a class for working with fractions. Only 3 private data members are needed: the int numerator, positive int denominator, and a double data member corresponding to the decimal equivalent for the fraction. The following methods should be in your class:
a. A default constructor that should use default arguments in case no initializers are included in the main. The fraction needs to be stored in reduced form. Make sure the denominator is not set to 0 or a negative value.
b. Add two fractions and store the sum in reduced form.
c. Subtract two fractions and store the difference in reduced form.
d. Multiply two fractions and store the product in reduced form.
e. Divide two fractions and store the quotient in reduced form.
f. Print a fraction, its decimal equivalent, and as a mixed fraction. For example, the fraction 7/2 should be 3 1/2.
Your main should instantiate two fractions and call each of the class methods. The two fractions should be printed a long with the sum, difference, product, quotient, and after adding 1 to the two fractions. (Please do not overload the operators for this program)."
Also in class for the main he wanted it to look like this:
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
|
int main()
{
Frac a(3,9), Frac b(10,6), sum, dif, prod, quo;
a,print();
b.print();
sum.add(a,b);
dif.subtract(a,b);
prod.mult(a,b);
quo.div(a,b);
cout << "sum is ";
sum.print();
cout << "difference is ";
dif.print();
cout << "product is ";
prod.print();
cout << "quotient is ";
quo.print();
a.addone();
b.addone();
cout << "After add one the fractions are ";
a.print();
b.print();
return 0;
|
What I have so far is
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
|
#include<iostream>
using namespace std;
class Frac
{
public:
Frac(int = 0, int = 1);
void print();
void add(Frac,Frac);
void subtract (Frac,Frac);
void mult(Frac, Frac);
void div (Frac, Frac);
void addone();
private:
int num, den;
double decimal;
};
Frac::Frac(int n, int d)
{
num = n;
if (d <= 0)
{
cout << "Error, denominator is equal to 0 or negative" << endl;
exit(0);
}
else
den = d;
decimal = n/(float)d;
}
}
void Frac::print()
{
cout << "The fraction form is " << num << "/" << den << endl;
cout << "The decimal form is " << decimal << endl;
}
void Frac::add(Frac one, Frac two)
{
}
|
I'm having trouble on the math part of the program (add,subtract,mult,div).
Can you guys help me out thanks! If you show me the addition part I think I can get the rest. And for addone would I just add the denominator to the numerator?