如何知道分数中的重复小数? [英] How to know the repeating decimal in a fraction?

查看:28
本文介绍了如何知道分数中的重复小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道分数是什么时候重复小数.这是函数.

I already know when a fraction is repeating decimals. Here is the function.

public bool IsRepeatingDecimal
{
    get
    {
        if (Numerator % Denominator == 0)
            return false;

        var primes = MathAlgorithms.Primes(Denominator);

        foreach (int n in primes)
        {
            if (n != 2 && n != 5)
                return true;
        }

        return false;
    }
}

现在,我正在尝试获取重复的数字.我正在查看这个网站:http://en.wikipedia.org/wiki/Repeating_decimal

Now, I'm trying to get the repeated number. I'm checking this web site: http://en.wikipedia.org/wiki/Repeating_decimal

public decimal RepeatingDecimal()
{
    if (!IsRepeatingDecimal) throw new InvalidOperationException("The fraction is not producing repeating decimals");

    int digitsToTake;
    switch (Denominator)
    {
        case 3:
        case 9: digitsToTake = 1; break;
        case 11: digitsToTake = 2; break;
        case 13: digitsToTake = 6; break;
        default: digitsToTake = Denominator - 1; break;
    }

    return MathExtensions.TruncateAt((decimal)Numerator / Denominator, digitsToTake);
}

但我真的意识到,有些数字有部分十进制有限,后来是无限的.例如:1/28

But I really realized, that some numbers has a partial decimal finite and later infinite. For example: 1/28

你知道更好的方法吗?还是算法?

Do you know a better way to do this? Or an Algorithm?

推荐答案

一个非常简单的算法是:实现长除法.记录您所做的每个中间部门.一旦您看到一个与您之前所做的相同的划分,您就会看到重复的内容.

A very simple algorithm is this: implement long division. Record every intermediate division you do. As soon as you see a division identical to the one you've done before, you have what's being repeated.

示例:7/13.

1. 13 goes into   7 0 times with remainder  7; bring down a 0.
2. 13 goes into  70 5 times with remainder  5; bring down a 0.
3. 13 goes into  50 3 times with remainder 11; bring down a 0.
4. 13 goes into 110 8 times with remainder  6; bring down a 0.
5. 13 goes into  60 4 times with remainder  8; bring down a 0.
6. 13 goes into  80 6 times with remainder  2; bring down a 0.
7. 13 goes into  20 1 time  with remainder  7; bring down a 0.
8. We have already seen 13/70 on line 2; so lines 2-7 have the repeating part

算法为我们提供了 538461 作为重复部分.我的计算器说 7/13 是 0.538461538.对我来说看起来不错!剩下的就是实现细节,或者寻找更好的算法!

The algorithm gives us 538461 as the repeating part. My calculator says 7/13 is 0.538461538. Looks right to me! All that remains are implementation details, or to find a better algorithm!

这篇关于如何知道分数中的重复小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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