How to output fraction instead of decimal number?

后端 未结 13 2087
余生分开走
余生分开走 2020-12-01 21:59

In C++, When I calculate 2/3, it will output decimal values, how can I just get the original format (i.e.g 2/3) instead of 0.66666667

Thanks

13条回答
  •  心在旅途
    2020-12-01 22:31

    This is impossible in general: floating point numbers are not precise and do not retain sufficient information to fully reconstruct a fraction.

    You could, however, write a function that heuristically finds an "optimal" approximation, whereby fractions with small numerators and denominators are preferred, as are fractions that have almost the same value as the floating point number.

    If you're in full control of the code, Oli's idea is better: don't throw away the information in the first place.

提交回复
热议问题