How can I turn a floating point number into the closest fraction represented by a byte numerator and denominator?

后端 未结 6 1035
南旧
南旧 2021-01-06 23:44

How can I write an algorithm that given a floating point number, and attempts to represent is as accurately as possible using a numerator and a denominator, both restricted

6条回答
  •  天命终不由人
    2021-01-06 23:47

    I would comment, but I don't have rep yet...

    Eric's answer above doesn't consider the case where an exact result is possible. For example, if you use 0.4 as input, then the representation should be 2/5, in which case you end up with a division by zero in the third iteration of the loop (r=0 on second loop => r = 1/r error on third).

    So you want to modify the while loop to exclude that option:

    while(true)
    

    should be

    while(r != 0)
    

提交回复
热议问题