日期:2014-05-18 浏览次数:20781 次
public class Fraction { private int _numerator; private int _denominator; public Fraction() { } public int Numerator { get { return _numerator; } set { _numerator = value; } } public int Denominator { get { return _denominator; } set { _denominator = value; } } private void Reduce() { int gcd = GreatCommonDivisor(_numerator, _denominator); _numerator /= gcd; _denominator /= gcd; } public void SumUp(Fraction f) { int lcm = LeastCommonMultiple(_denominator, f.Denominator); int f1_Numerator = _numerator * (lcm / _denominator); int f2_Numerator = f.Numerator * (lcm / f.Denominator); _numerator = f1_Numerator + f2_Numerator; _denominator = lcm; Reduce(); } private int GreatCommonDivisor(int a, int b) { int dividend, divisor, tmp; dividend = a > b ? a : b; divisor = a < b ? a : b; while (dividend % divisor != 0) { tmp = divisor; divisor = dividend % divisor; dividend = tmp; } return divisor; } private int LeastCommonMultiple(int a, int b) { int gcd, lcm; gcd = GreatCommonDivisor(a, b); lcm = (a / gcd) * (b / gcd) * gcd; return lcm; } public override string ToString() { return string.Format("{0}/{1}", _numerator, _denominator); } }