コード例 #1
0
ファイル: Rational.cs プロジェクト: nzvcv/UrFU
        public static bool TryParse(string input, out Rational result)
        {
            result = new Rational();

            if (input.LastIndexOf('-') > 0)
            {
                return(false);
            }

            string[] fullNumber = input.Split('.');

            if (fullNumber.Length > 2)
            {
                return(false);
            }

            if (fullNumber.Length == 1 && !fullNumber[0].Contains(":"))
            {
                try
                {
                    result.Numerator = int.Parse(fullNumber[0]);
                }
                catch (Exception)
                {
                    return(false);
                }

                return(true);
            }

            if (fullNumber.Length == 1)
            {
                try
                {
                    var fraction = fullNumber[0].Split(':');
                    result.Numerator   = int.Parse(fraction[0]);
                    result.Denominator = int.Parse(fraction[1]);

                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            try
            {
                var fraction = fullNumber[1].Split(':');

                if (fraction.Length > 2)
                {
                    return(false);
                }

                int sign = 1;

                if (input.LastIndexOf('-') == 0)
                {
                    sign = -1;
                }


                int z           = int.Parse(fullNumber[0]);
                int numerator   = int.Parse(fraction[0]);
                int denumerator = int.Parse(fraction[1]);


                result.Denominator = denumerator;
                result.Numerator   = z * denumerator + sign * numerator;
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }