将小数转换为分数c ++ [英] Converting decimal to fraction c++

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

问题描述

什么是一个算法,我可以用来转换和输入十进制数为一个分数形式在c ++。例如,如果我输入1.25,我想转换输出为1 1/4。

What is an algorithm I can use to convert and input decimal number into a fraction form in c++. For example if I enter 1.25 I would like the conversion to output to be 1 1/4.

推荐答案

然后拿gcd。使用欧氏算法 http://en.wikipedia.org/wiki/Euclidean_algorithm

First get the fractional part and then take the gcd. Use the Euclidean algorithm http://en.wikipedia.org/wiki/Euclidean_algorithm

void foo(double input)
{
    double integral = std::floor(input);
    double frac = input - integral;

    const long precision = 1000000000; // This is the accuracy.

    long gcd_ = gcd(round(frac * precision), precision);

    long denominator = precision / gcd_;
    long numerator = round(frac * precision) / gcd_;

    std::cout << integral << " + ";
    std::cout << numerator << " / " << denominator << std::endl;
}

long gcd(long a, long b)
{
    if (a == 0)
        return b;
    else if (b == 0)
        return a;

    if (a < b)
        return gcd(a, b % a);
    else
        return gcd(b, a % b);
}

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

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