Ejemplo n.º 1
0
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args)
        {
            ArrayStack myStack = new ArrayStack();
            StackCalculator myCalculator = new StackCalculator(myStack);
            myCalculator.Push(3);
            myCalculator.Push(2);
            myCalculator.Push(1);
            myCalculator.Add();
            myCalculator.Multiply();
            Console.WriteLine(myCalculator.Result());

            ListStack myStack2 = new ListStack();
            StackCalculator myCalculator2 = new StackCalculator(myStack2);
            myCalculator2.Push(1);
            myCalculator2.Push(2);
            myCalculator2.Push(3);
            myCalculator2.Add();
            myCalculator2.Multiply();
            Console.WriteLine(myCalculator2.Result());
        }
Ejemplo n.º 2
0
        public static int Calculate(string expression)
        {
            int firstNumber = 0;
            int i = 0;
            bool isNegative = false;

            if (expression[0] == '-')
            {
                isNegative = true;
                ++i;
            }

            while (expression[i] >= '0' && expression[i] <= '9')
            {
                firstNumber = firstNumber * 10 + (int)expression[i] - 48;
                ++i;
                if (i == expression.Length)
                {
                    if (isNegative)
                    {
                        firstNumber = 0 - firstNumber;
                    }
                    return firstNumber;
                }
            }

            if (isNegative)
            {
                firstNumber = 0 - firstNumber;
            }

            int operationPlace = i;
            ++i;
            int secondNumber = 0;

            while (i < expression.Length)
            {
                secondNumber = secondNumber * 10 + (int)expression[i] - 48;
                ++i;
            }

            var calc = new StackCalculator(new Stack());
            calc.Push(firstNumber);
            calc.Push(secondNumber);
            switch (expression[operationPlace])
            {
                case '/':
                    calc.Divide();
                    break;
                case '*':
                    calc.Multiply();
                    break;
                case '+':
                    calc.Add();
                    break;
                case '-':
                    calc.Subtract();
                    break;
            }
            return calc.Result();
        }