Hello, I am writing a class for a mixed number, and I have all of the operator overloads working and such when it comes to other mixed number objects. But My conversion constructor for if just an int is entered is not working. If someone could take a quick peak and see if anything jumps out, it would be much appreciated.
Mixed operator+(Mixed& f1, Mixed& f2){
// this is the + operator overload
Mixed r;
f1.ToFraction();
f2.ToFraction();
// load result Mixed with sum of adjusted numerators
r.numerator = (f1.numerator*f2.denominator)
+ (f2.numerator*f1.denominator);
// load result with the common denominator
r.denominator = f1.denominator * f2.denominator;
f1.Simplify();
f2.Simplify();
r.Simplify();
return r; // return the result Fraction
}
ostream& operator << (ostream& s, Mixed& m){
// This is an operator overload for the insertion ( << ) operator
if (m.denominator < 0){
m.denominator = m.denominator * -1;
m.whole = m.whole * -1;
}
if (m.numerator < 0 && m.whole < 0){
m.numerator = m.numerator * -1;
}
if (m.whole == 0){
s << m.numerator << '/' << m.denominator;
}
else {
s << m.whole << ' ' << m.numerator << '/' << m.denominator;
}
return s;
}
These are the functions used in the above operators. The ToFraction() function converts the Mixed number into an improper fraction. The Simplify() function converts improper functions back into mixed numnbers, as well as reduces fractions.
void Mixed::Simplify(){
// This function converts an improper fraction back into a mixed number and reduces the fraction
// If it is an improper fraction
if (whole == 0){
whole = numerator / denominator;
numerator = numerator % denominator;
}
int k, i;
if(numerator < denominator){
k = denominator;
}
else{
k = numerator;
}
for (i = k; i > 0; i--){
if(numerator % i == 0 && denominator % i == 0){
numerator = numerator / i;
denominator = denominator / i;
}
}
1 2 3 4 5 6 7 8 9 10 11 12
void Mixed::ToFraction(){
// This Function converts the mixed number into an improper fraction
int temp;
temp = denominator * whole;
numerator = temp + numerator;
whole = 0;
}
EDIT: actually you might not be able to do that because your operators are modifying the objects passed to them.... hang on...
EDIT 2:
yeah you have to be const correct. +, -, etc operators should not be modifying the passed parameters. You'll have to redesign those functions slightly.
Here's a different way to do the + operator. You could change your other operators to do it a similar way.
But this also expects more out of Simplify.... You might end up with something like 3 5/4 (which you would want to simplify to 4 1/4, but it doesn't look like your Simplify would cover that)
Well, I couldnt do EXACTLY that, because in order to do the math, I had to change the Mixed number to a fraction. But I just created a copy and worked with that in the function, and it works perfectly now. Thank you very much for your ideas and help, I really appreciate it.