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?
How to convert real number into fraction
Collapse
X
-
Andrew EsmundoTags: None -
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. -
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;Comment
-
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?Comment
Comment