我正在寻找一个库或现有代码来简化分数。
有没有人手头有任何东西或任何链接?
PS我已经了解这个过程但真的不想重写轮子
更新
好的,我已经检查了CodeProject 上的分数库, 但是我遇到的问题比简化分数要复杂一些。
我必须减少可能是 20% / 50% / 30% 的百分比分割(总是等于 100%)
我正在寻找一个库或现有代码来简化分数。
有没有人手头有任何东西或任何链接?
PS我已经了解这个过程但真的不想重写轮子
好的,我已经检查了CodeProject 上的分数库, 但是我遇到的问题比简化分数要复杂一些。
我必须减少可能是 20% / 50% / 30% 的百分比分割(总是等于 100%)
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).
您可以使用免费的F# Power Pack库中的 Microsoft.FSharp.Math.BigRational。虽然它依赖于 F#(它是免费的,并且包含在 VS2010 中),但它可以从 C# 中使用。
BigRational reduced = BigRational.FromInt(4)/BigRational.FromInt(6);
Console.WriteLine(reduced);
2/3
Console.WriteLine(reduced.Numerator);
2
Console.WriteLine(reduced.Denominator);
3
这个库看起来可能是你需要的:
var f = new Fraction(numerator, denominator);
numerator = f.Numerator;
denominator = f.Denominator;
虽然,我还没有测试过它,所以看起来你可能需要玩弄它才能让它工作。
我见过的分数(又名 Rational)的最佳示例是Timothy Budd 的“C++ 中的经典数据结构”。他的实现非常好。它包括 GCD 算法的简单实现。
适应 C# 应该不难。
自定义解决方案:
void simplify(int[] numbers)
{
for (int divideBy = 50; divideBy > 0; divideBy--)
{
bool divisible = true;
foreach (int cur in numbers)
{
//check for divisibility
if ((int)(cur/divideBy)*divideBy!=cur){
divisible = false;
break;
}
}
if (divisible)
{
for (int i = 0; i < numbers.GetLength(0);i++ )
{
numbers[i] /= divideBy;
}
}
}
}
示例用法:
int [] percentages = {20,30,50};
simplify(percentages);
foreach (int p in percentages)
{
Console.WriteLine(p);
}
输出:
2
3
5
顺便说一句,这是我的第一个 c# 程序。以为尝试一种新语言只是一个有趣的问题,现在我恋爱了!它就像 Java,但我希望有所不同的一切正是我想要的
<3 c#
编辑:顺便说一句,如果它用于您的 Main 类,请不要忘记将其设为 static void。