Beispiel #1
0
        static void Main(string[] args)
        {
            printMessage("Welcome to Fractionator!\nI will help you perform basic operations (+, -, *, /) with fractional numbers");
            printMessage("Example: ? 1/7 + 3_8/16");

            while (true)
            {
                string input = Console.ReadLine();

                if (input.ToLower().Trim().Equals("exit"))
                {
                    break;
                }

                if (input[0].Equals('?'))
                {
                    FractionNumber f1, f2;
                    string         oper;

                    if (FractionExpression.tryParse(input.Trim('?'), out f1, out f2, out oper))
                    {
                        Console.WriteLine("Result: " + FractionExpression.executeOperation(f1, f2, oper));
                    }
                    else
                    {
                        printMessage("Invalid expression!");
                    }
                }
                else
                {
                    printMessage("Wrong input!");
                }
            }
        }
Beispiel #2
0
        public static bool tryParse(string expr, out FractionNumber f1, out FractionNumber f2, out string oper)
        {
            f1   = new FractionNumber(0);
            f2   = new FractionNumber(0);
            oper = "";

            string[] pieces = expr.Split(' ');

            List <string> expPieces = new List <string>();

            for (int p = 0; p < pieces.Length; p++)
            {
                if (pieces[p].Trim().Length > 0)
                {
                    expPieces.Add(pieces[p]);
                    if (expPieces.Count == 3)
                    {
                        break;
                    }
                }
            }

            // Min set for operation
            if (expPieces.Count < 3)
            {
                return(false);
            }

            // Valid oper sign
            List <string> operands = new List <string> {
                "+", "-", "*", "/"
            };

            if (expPieces[1].Length != 1 || !operands.Contains(expPieces[1]))
            {
                return(false);
            }

            oper = expPieces[1];

            // Parse each fraction number
            if (!FractionExpression.tryParse(expPieces[0], out f1) ||
                !FractionExpression.tryParse(expPieces[2], out f2))
            {
                return(false);
            }

            return(true);
        }