如何简化分数? [英] How to simplify fractions?

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

问题描述

如何简化在C#中的一小部分?例如,给定 1 11/6 ,我需要它简化为 2 5/6

How to simplify a fraction in C#? For example, given 1 11/6, I need it simplified to 2 5/6.

推荐答案

如果你想要的是把你的分数变成一个混合的数字,其小数部分就像是承担了以前的答案正确的分数,你只需要添加分子/分母来的数量的整数部分,并设置为分子分子分母%。使用循环为,这是完全没有必要的。

If all you want is to turn your fraction into a mixed number whose fractional part is a proper fraction like the previous answers assumed, you only need to add numerator / denominator to the whole part of the number and set the numerator to numerator % denominator. Using loops for this is completely unnecessary.

然而,术语简化,通常是指减少一小部分来的最低条件。你的例子并不清楚是否希望为好,因为这个例子是在其最简两种方式。

However the term "simplify" usually refers to reducing a fraction to its lowest terms. Your example does not make clear whether you want that as well, as the example is in its lowest terms either way.

下面是一个C#类,标准化的混合数字,例如每个数字有且只有一个表示:小数部分总是正确,并始终在其最低而言,分母总是正的和整个部分的符号始终相同分子的符号

Here's a C# class that normalizes a mixed number, such that each number has exactly one representation: The fractional part is always proper and always in its lowest terms, the denominator is always positive and the sign of the whole part is always the same as the sign of the numerator.

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);
    }
}



使用范例:

Sample usage:

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

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

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