Advertisement

fractions

Started by October 21, 2000 01:18 PM
12 comments, last by pizzaman 24 years, 2 months ago
thanks for the help people.
i am the best
To print f as a fraction with a numerator of n (in C):


float f = 0.333f;
int n = 1;

printf("%d/%d", n, (int)((float)n / f));

The only problem with this approach is that you must supply a numerator.


"No army has ever marched into battle thinking the Creator had sided with their enemy." - Terry Goodkind
Advertisement
Well, assuming that you can alread add fractions you could do this (Recalling my study of series in calculus):

Say you have an arbitrary decimal say 0.23598375943.
Well this can be represented in fractions as such:
2/10 + 3/100 + 5/1000 + 9/10000 + ...

Which can also be written as such:
n/10^i where i is the decimal place and n is the number at this spot.

I believe this should get you on your way to converting decimals into fractions.
---Ranok---
Thanks for all the help. I''ve written my own function to convert float''s to strings. I''ve also found out that VC++ 6 is picky with strings, and doesn''t support the << operator for them . I got around that, but I shouldn''t have to do that.

Now all I have to do is make the conversion function (which should include a pattern-matching algorithm), and implement it in my rational (another name for fractions?) class. Then I''ll have something that acts just like any other data type, including allowing conversions.


"Whoever performs only his duty is not doing his duty." --Bahya ibn Pakuda
"If a man does not keep pace with his companions, perhaps it is because he hears a different drummer. Let him step to the music he hears, however measured or far away"--Henry David Thoreau

This topic is closed to new replies.

Advertisement