如何降低比例到最低期限 [英] How to reduce ratio to lowest term

查看:85
本文介绍了如何降低比例到最低期限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将比率降低到最低值



例如:550:150到11:6使用c#

How to reduce ratio to lowest term

for example : 550:150 to 11:6 using c#

推荐答案

见这里: http://stackoverflow.com/questions/5287514/how-to-简化分数 [ ^ ] - 这是完全相同的过程。
See here: http://stackoverflow.com/questions/5287514/how-to-simplify-fractions[^] - it's exactly the same process.


不容易:



首先,您必须创建一个方法来查找所有因素一个给定的数字并将它们输出为IEnumerable< int>

Not easily:

First you have to create a method that finds all factors of a given number and output them as a IEnumerable<int>
public IEnumerable<int> Factorize(int number) {
    int max = (int)(number/2);  
    for(int factor = 1; factor <= max; ++factor) { 
        if(number % factor == 0) {
            yield return factor;
        }
    }
    yield number;
}
</int>





现在你有了这些因素,你需要找到两个数字共有的因子(公分母)< br $>




Now you have the factors, you need to find factors common to both numbers (common denominator)

public IEnumerable<int> CommonDenominators(int numberLeft,int NumberRight) {
    return Factorize(numberLeft).Union(Factorize(numberRight);
}
</int>





实际上: ,你可以调整它以返回最高(我一直认为是最低的,这将是1?)共同点:





Actually:,You can adapt that to return the highest (i always thought is was the lowest, which would be 1?) common denominator:

public int HighestCommonDenominator(int numberLeft,int NumberRight) {
    return Factorize(numberLeft).Union(Factorize(numberRight).Max(n=>n);
}





编辑:如果没有其他共同点,即17:181那么数字1将是retu rned,所以它仍然准确



然后将两个数字除以这个数字:





If there are no other common denominators, i.e. 17:181 then the number 1 will be returned, so it's still accurate

Then just divide both numbers by that number:

int left = 550;
int right = 150:
int highestCommonDenominator = HighestCommonDenominator(left, right );
int lowestLeft = left / lowestCommonDenominator;
int lowestRight = right / lowestCommonDenominator;  





我没有测试过代码,但必需品已经存在



希望有帮助:)



I haven't tested the code but the essentials are there

Hope that helps :)


这篇关于如何降低比例到最低期限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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