c# - 如何化简分数?

标签 c# math fractions

如何在 C# 中化简分数?例如,给定 1 11/6,我需要将其简化为 2 5/6

最佳答案

如果你只是想把你的分数变成一个带分数,它的小数部分是一个正确的分数,就像前面的答案假设的那样,你只需要在整个部分添加numerator/denominator number 并将分子设置为 numerator % denominator。为此使用循环是完全没有必要的。

然而,术语“简化”通常指的是将分数减少到最低项。您的示例并不清楚您是否也需要它,因为无论哪种方式,该示例都是最低限度的。

这是一个 C# 类,它对混合数进行归一化,这样每个数字都只有一个表示形式:小数部分始终是适当的并且始终是最低项,分母始终是正数并且整个部分的符号始终是与分子的符号相同。

using System;

public class MixedNumber {
    public MixedNumber(int wholePart, int num, int denom)
    {  
        WholePart = wholePart;
        Numerator = num;
        Denominator = denom;
        Normalize();
    }

    public int WholePart { get; private set; }
    public int Numerator { get; private set; }
    public int Denominator { get; private set; }

    private int GCD(int a, int b)
    {  
        while(b != 0)
        {  
            int t = b;
            b = a % b;
            a = t;
        }
        return a;
    }

    private void Reduce(int x) {
        Numerator /= x;
        Denominator /= x;
    }

    private void Normalize() {
        // Add the whole part to the fraction so that we don't have to check its sign later
        Numerator += WholePart * Denominator;

        // Reduce the fraction to be in lowest terms
        Reduce(GCD(Numerator, Denominator));

        // Make it so that the denominator is always positive
        Reduce(Math.Sign(Denominator));

        // Turn num/denom into a proper fraction and add to wholePart appropriately
        WholePart = Numerator / Denominator;
        Numerator %= Denominator;
    }

    override public String ToString() {
        return String.Format("{0} {1}/{2}", WholePart, Numerator, Denominator);
    }
}

示例用法:

csharp> new MixedNumber(1,11,6);     
2 5/6
csharp> new MixedNumber(1,10,6);   
2 2/3
csharp> new MixedNumber(-2,10,6);  
0 -1/3
csharp> new MixedNumber(-1,-10,6); 
-2 -2/3

关于c# - 如何化简分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287514/

相关文章:

c - 反转长 double 的指数给了我一个疯狂的结果

java - 如何以给定的概率传播随机值?

c++ - 添加分数和类别 - Woot

c# - mysql 不会从 C# 中保存 double

c# - Assert.AreEqual 对于没有增量的 float

javascript - 从具有多个球的圆形边界反弹?

javascript - 3d 数学 : screen space to world space

Java 不运行这个 for 循环

c# - 如何在字符的第一个实例处截断字符串?

c# - 如何获取模型属性的 id 以便与 MVC3 中的自定义 IClientValidatable 一起使用