读书人

请大家帮忙看看这个程序如何写?多谢了

发布时间: 2011-12-30 23:30:45 作者: rapoo

请大家帮忙看看这个程序怎么写?谢谢了~~~
编写程序相加两个分数,并将它们的和以化简后的分数形式表现出来。程序使用类Fraction来存放分数的分子和分母,具有方法Reduce来化简结果。

[解决办法]

C# code
    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);        }    } 

读书人网 >C#

热点推荐