Fractions?

Oct 16, 2011 at 1:16am
Hello everyone, I am working on a fraction class.

But I am stuck on the code, the part where after the simplification of the fraction I need to diplay it in the right format.
Exmp:

1
2
3
4
5
when 2/4 / 1/3 = 3/2// this after simplified

// but I am looking to display it like:

3/2 like 1 1/2


Any help or hint is greatly appreciated.
Oct 16, 2011 at 3:59am
You could create an int variable and set it equal to numerator/denominator. This will do integer division meaning that it will truncate the remainder, and leave you with just the first part of the result you want to display. Then, you can take that value, multiply it by denominator, and subtract the result from numerator. Then just display what is now your numerator and denominator. Pretty sure this should work. Hope that makes sense.
Oct 16, 2011 at 8:57am
Thanks freddy92,

It does make sense in math, but I cannot figure out where to implement on my code?
[code]
// you are saying
int x;

x = num/den;

x = x*den - num;// where do I implement this on the code.
Last edited on Oct 16, 2011 at 2:36pm
Oct 16, 2011 at 10:00am
In your operator <<, just do what I said above. You could start by declaring some temporary variables for the numerator and denominator, as well as one for the number out in front. Set that variable equal to numerator/denominator, and numerator equal to numerator minus the front number times denominator. Then just print these values out in the appropriate order.
Oct 16, 2011 at 9:45pm
Thanks a lot freddy92,

I was able to do that however I had to change operator << to non constont.
Was told that that is not a good idea.

Oct 16, 2011 at 11:58pm
You mean you had to pass the fraction class by non-constant reference? I don't see why you would have to do that. Everything passed to it should be able to be const.
Oct 17, 2011 at 3:22am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ostream& operator << (ostream& out,  CFraction& output)
{
	int x;
	if (output.numerator > output.denominator)
	{
		x = output.numerator / output.denominator;
		output.numerator = output.numerator - ( x * output.denominator);
	
		out << x  << " " << output.numerator << "/" << output.denominator;
	}
	else
		out << output.numerator << "/" << output.denominator;

	return out;
}


This is what it looks like.
Oct 17, 2011 at 3:40am
I said to declare some new variables in your function (called num and denom or something) and put the value of output.numerator in num and output.denominator in denom. This is because you'll be changing the value of the numerator, but you don't want to actually change the value of the numerator in the fraction object that you pass in. Just declare those variables and use them in place of the numerator and denominator in the Fraction object, and you can make it const again.
Oct 17, 2011 at 4:55am
Thanks again freddy92 .

Yes you did, I just missed that.
Topic archived. No new replies allowed.