比较c#中的2个比率值

时间:2015-12-26 00:31:51

标签: c# c#-4.0

借助SO Calculate a Ratio in C#中的此链接  我能够在c#

中计算比率
var gcd = GCD(A, B);
return string.Format("{0}:{1}", A / gcd, B / gcd)
static int GCD(int a, int b) {
    return b == 0 ? a : GCD(b, a % b);
}

现在我如何比较2比值

 if A:B< 1:10 my result =1

 if A:B >1:10  my result=0

那么如何在C#中添加这个比例比较如何检查我的口粮是否小于1:10 ??

1 个答案:

答案 0 :(得分:0)

您可以为比率创建一个类(带正分母) 实现IComparable接口和比较运算符也是有意义的:

public class Ratio : IComparable<Ratio>
{
    public readonly int A;
    public readonly int B;

    public Ratio(int a, int b)
    {
        if (b < 0)
        {
            a = -a;
            b = -b;
        }

        A = a;
        B = b;
    }

    public int CompareTo(Ratio other)
    {
        return A * other.B - B * other.A;
    }

    public static bool operator <(Ratio r1, Ratio r2)
    {
        return r1.CompareTo(r2) < 0;
    }

    public static bool operator >(Ratio r1, Ratio r2)
    {
        return r1.CompareTo(r2) > 0;
    }

    public static bool operator >=(Ratio r1, Ratio r2)
    {
        return r1.CompareTo(r2) >= 0;
    }

    public static bool operator <=(Ratio r1, Ratio r2)
    {
        return r1.CompareTo(r2) <= 0;
    }

    public static bool operator ==(Ratio r1, Ratio r2)
    {
        return r1.CompareTo(r2) == 0;
    }

    public static bool operator !=(Ratio r1, Ratio r2)
    {
        return r1.CompareTo(r2) != 0;
    }
}

样本用法:

var r1 = new Ratio(1, 10); // 1/10
var r2 = new Ratio(2, 20); // 2/20

Console.WriteLine(r1 >= r2); // true
Console.WriteLine(r1 > r2);  // false
Console.WriteLine(r1 < r2);  // false
Console.WriteLine(r1 == r2); // true
var r1 = new Ratio(1, 10); // 1/10
var r2 = new Ratio(1, 11); // 1/11

Console.WriteLine(r1 >= r2); // true
var r1 = new Ratio(1, 10); // 1/10
var r2 = new Ratio(1,  9); // 1/9

Console.WriteLine(r1 >= r2); // false

或者您可以使用上述CompareTo方法的逻辑 2个比率a/bc/d其中b,d > 0
当且仅当a/b > c/d时才a*d > c*b为真。