小数到小数转换 [英] Decimal to fraction conversion

查看:103
本文介绍了小数到小数转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

面试中我遇到以下问题:

I got the following question for an interview:

程序将小数更改为最接近的分数.

Program to change a decimal to the nearest fraction.

示例: 0.12345 => 2649/20000

Example: 0.12345 => 2649/20000

0.34 => 17/50

0.34 => 17/50

解决此问题的最佳方法是什么?

What is the best approach to solve this?

推荐答案

十进制数是一个分数,其分母为10的幂(并且对于任何数字基来说都是类似的).所以0.34是34/100现在只需取消公因子,即将分子和分母除以它们的最大公因数.

A decimal number is a fraction whose denominator is a power of ten (and similarly for any number base). So 0.34 is 34/100. Now just cancel the common factor, i.e. divide both numerator and denominator by their greatest common divisor.

您可以使用标准算法找到GCD,我留给您查找.

You can find the GCD with a standard algorithm, which I leave to you to find.

这篇关于小数到小数转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆