栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将浮点数转换为字符串分数表示形式

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将浮点数转换为字符串分数表示形式

最简单的方法可能是使用反复试验。

public static String toFraction(double d, int factor) {    StringBuilder sb = new StringBuilder();    if (d < 0) {        sb.append('-');        d = -d;    }    long l = (long) d;    if (l != 0) sb.append(l);    d -= l;    double error = Math.abs(d);    int bestDenominator = 1;    for(int i=2;i<=factor;i++) {        double error2 = Math.abs(d - (double) Math.round(d * i) / i);        if (error2 < error) { error = error2; bestDenominator = i;        }    }    if (bestDenominator > 1)        sb.append(' ').append(Math.round(d * bestDenominator)).append('/') .append(bestDenominator);    return sb.toString();}public static void main(String... args)  {    System.out.println(toFraction(1.3333, 1000));    System.out.println(toFraction(1.1428, 1000));    for(int i=1;i<100000000;i*=10) {        System.out.println("PI "+i+": "+toFraction(3.1415926535897932385, i));    }}

版画

1 1/31 1/7PI 1: 3PI 10: 3 1/7PI 100: 3 14/99PI 1000: 3 16/113PI 10000: 3 16/113PI 100000: 3 14093/99532PI 1000000: 3 140914/995207PI 10000000: 3 244252/1725033


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/515817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号