By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,650 Members | 1,778 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,650 IT Pros & Developers. It's quick & easy.

How to convert real number into fraction

P: n/a
Im trying to write a program for c that promts the user for a non-negative real number and outputs the fraction closest to that number. For example: if I input 42.7488 the the output is 171/4. Would I use an if loop? Would it be correct to change the real number into an integer and find the greatest common denominator?
Oct 24 '10 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 2,398
Start with finding a mathematical algorithm for this. Don't worry about writing a computer program until after that.

Did your teacher provide any hints or suggestions for what algorithm to use?

By the way, I think what you're trying to do is find a rational approximation for a real number. The word fraction is ambiguous.
Oct 24 '10 #2

100+
P: 687
Unless the number is rational, there is no such thing as "the closest" one, otherwise the number itself is the closest. You need to set some precision and stop after it's reached ( in the example it's 0.0012)
e.g.
for each i from 2
N = [x*i]; if N/i or (N+1)/i is close enough then stop;
Oct 25 '10 #3

Expert 100+
P: 2,398
171/4 is certainly not the closest rational approximation to 42.7488. What is your criteria for best and/or close enough?

171/4 = 42.75
but 427488/10000 is precisely 42.7488
(and the latter ratio can be reduced to 26718/625)
What is it that makes the first ratio better than either of the two exact forms?
Oct 25 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.