如何简化C#中的分数? [英] How to simplify fractions in C#?
问题描述
我正在寻找一个库或现有代码来简化分数.
I'm looking for a library or existing code to simplify fractions.
有人在手或链接吗?
P.S.我已经了解此过程,但真的不想重写轮子
P.S. I already understand the process but really don't want to rewrite the wheel
好吧,我已经检出了CodeProject上的分数库 但是我遇到的问题比简化分数要复杂一些.
Ok i've checked out the fraction library on the CodeProject BUT the problem I have is a little bit tricker than simplifying a fraction.
我必须减小百分比拆分,该比例可能是20%/50%/30%(始终等于100%)
I have to reduce a percentage split which could be 20% / 50% / 30% (always equal to 100%)
推荐答案
我认为您只需要将所有数字除以GCD.
I think you just need to divide by the GCD of all the numbers.
void Simplify(int[] numbers)
{
int gcd = GCD(numbers);
for (int i = 0; i < numbers.Length; i++)
numbers[i] /= gcd;
}
int GCD(int a, int b)
{
while (b > 0)
{
int rem = a % b;
a = b;
b = rem;
}
return a;
}
int GCD(int[] args)
{
// using LINQ:
return args.Aggregate((gcd, arg) => GCD(gcd, arg));
}
我还没有尝试过代码,但是看起来很简单就对了(假设您的数字都是正整数,并且您没有传递空数组).
I haven't tried the code, but it seems simple enough to be right (assuming your numbers are all positive integers and you don't pass an empty array).
这篇关于如何简化C#中的分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!