Hi,

How to make at code that calculator will operate with 3 numbers (Example: 15 - 2 * 5) and that multiplication and division have precedence over addition and subtraction ?

At that code it operates just with 2 numbers:

int num1;
            int num2;
            string operand;
            float answer;

            Console.Write("Please enter the first integer: ");
            num1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Please enter an operand (+, -, /, *): ");
            operand = Console.ReadLine();

            Console.Write("Please enter the second integer: ");
            num2 = Convert.ToInt32(Console.ReadLine());

            switch (operand)
            {
                case "-":
                    answer = num1 - num2;
                    break;
                case "+":
                    answer = num1 + num2;
                    break;
                case "/":
                    answer = num1 / num2;
                    break;
                case "*":
                    answer = num1 * num2;
                    break;
                default:
                    answer = 0;
                    break;
            }
            Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " = " + answer.ToString());

            Console.ReadLine();

Any help is welcome.

Regards,
bisiii

Recommended Answers

All 7 Replies

This is "relativly" easy.
All you have to do is write a "recursive descendant parser" :cool:
Look at these snippets on how I did that. It was really fun!!!
http://www.daniweb.com/code/snippet217187.html
http://www.daniweb.com/code/snippet217186.html
http://www.daniweb.com/code/snippet217185.html
Put all these together in a Console Application and see for yourself.
Success! Ask if you have any more questions.

Take a look into the code I did only for you. Its a code, which allows the user to insert as many numbers and operands as he wants to create a formula.
On the end, when he wants to create an out put, he only inserts the enter after number:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jan22Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            bool bEnd = false;
            decimal total = 0M;
            decimal number = 0M;
            string strOperand = null;
            string strFormula = null;
            int counter = 1;

            Console.WriteLine("Calculator: Please enter number by number, seperated by operands.");
            Console.WriteLine("To get the result, simply write the equals sing just after number (X=)");
            do
            {
                string word = GetCounter(counter);              

                Console.WriteLine("Please enter the " + word + " number:");
                string strNumber = Console.ReadLine();

                
                if (strNumber.Contains("="))
                {
                    strNumber = strNumber.Remove(strNumber.Length - 1, 1);
                    bEnd = true;
                }
                bool bChecking = CheckingNumber(strNumber);
                if (bChecking)
                {
                    strFormula += strNumber;
                    counter++;
                    number = Convert.ToDecimal(strNumber);
                    total = GetTotal(number, total, strOperand);

                    bChecking = false;
                    while (!bChecking && !bEnd)
                    {
                        Console.WriteLine("Please enter the operand (+, -, /, *):");
                        strOperand = Console.ReadLine();
                        bChecking = CheckingOperand(strOperand);
                        if (bChecking)
                            strFormula += strOperand;
                        else
                            Console.WriteLine("Wrong operand.");
                    }
                }
                else
                    Console.WriteLine("This is not the number.");
            }
            while (!bEnd);

            //on the end it shows the final result:
            strFormula = strFormula + "=";
            Console.WriteLine("{0}{1}", strFormula, total.ToString());
            Console.ReadLine();
        }

        public static string GetCounter(int counter)
        {
            string word = null;
            string[] words = { "1st", "2nd", "3rd" };
            if (counter < 3)
                word = words[counter - 1];
            else
                word = counter + "th";
            return word;
        }

        public static bool CheckingNumber(string answer)
        {
            decimal value = 0M;
            bool bChecking = decimal.TryParse(answer, out value);
            return bChecking;
        }

        public static bool CheckingOperand(string answer)
        {
            string[] operands = { "*", "/", "+", "-" };
            for (int i = 0; i < operands.Length; i++)
                if (operands[i] == answer)
                    return true;
            return false;
        }

        public static decimal GetTotal(decimal number, decimal total, string operand)
        {
            if (operand != null)
            {
                if (total != 0)
                {
                    switch (operand)
                    {
                        case ("*"):
                            {
                                total = total * number;
                                break;
                            }
                        case ("/"):
                            {
                                total = total / number;
                                break;
                            }
                        case ("+"):
                            {
                                total = total + number;
                                break;
                            }
                        case ("-"):
                            {
                                total = total - number;
                                break;
                            }
                    }
                }
                else
                    total = number;
            }
            else
                total = number;
            return total;
        }
    }
}

Take a slow look into it, becuase it includes almost everytihng (from catching error, to notifying users what he has to do in the next step,...)

BTW: the equals sing (=) would be better to put together with all the operands, dont you thing? So when you will write "=", instead of operands, the message of total will apear.

GUESS WHAT: this is what I give you for your homework. Just in case if you wont manage it to work it out, let me know (maybe I can help you :)).

bye
Mitja

Nice try Mitja, but what the OP wants is that 15 - 2 * 5 is equal to 5 and not equal to 65!

I see...

Thank you both for your help but as I see these codes are a little but too much complicated for my project. I'm in first year of programming college and we didn't take so complex tasks yet. Doesn't it go easier ? I mean to create a menu if user want to calculate with 2 or 3 numbers and then create a code with IF loops and these beginning methods ? Because when I create a programme I need to explain it to assistant. If I would create code in that way, I'm sure I wouldn't know to explain it. So I need to know how make it in easier way.
But thank you for your posts, maybe it would be more helpful in next years.

You could try the stack approach then.
Perhaps work out this simple example a bit:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SimpleStacks
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<char> oper = new Stack<char>();
            Stack<int> num = new Stack<int>();
            char ch;
            bool err = false;
            // To keep it simple initially only allow 
            // 1 digit expressions with operators + and -
            // and 5 digits 1,2,3,4 and 5
            string text = "2+4- 3 -5"; // or use Console.ReadLine
            // Build up stacks from text expression
            char[] chstr = text.ToCharArray();
            for (int i=0; i < chstr.Length; i++)
            {
                ch = chstr[i];
                if (IsOperator(ch))
                    oper.Push(ch);
                else if (IsNumber(ch)) // or char.IsDigit(ch)                  
                    num.Push(Convert.ToInt32(ch - '0'));
                else if (char.IsWhiteSpace(ch)) 
                    continue; //omit space,tab etc.
                else
                {
                    err = true;
                    break;
                }
            }
           
            foreach (int i in num)
                Console.Write(i);
            Console.WriteLine();

            // Calculate result
            if (err)
                Console.WriteLine("*** Error in expression.");
            else
            {
                //Reverse stacks
                oper = new Stack<char>(oper);
                num = new Stack<int>(num);
                
                int op1, op2;
                int result;
                while (num.Count > 1)
                {
                    op1 = num.Pop();
                    op2 = num.Pop();
                    switch (oper.Pop())
                    {
                        case '+':
                            result = op1 + op2;
                            num.Push(result);
                            break;
                        case '-':
                            result = op1 - op2;
                            num.Push(result);
                            break;
                        default:
                            break;
                    }
                }              
            }
            // On the num stack there should be only one number, the final result.
            Console.WriteLine("The result of the calculation is: {0}", num.Pop());
            Console.ReadKey();
        }

        static bool IsOperator(char ch)
        {
            return ch == '+' || ch == '-';
        }

        static bool IsNumber(char ch)
        {
            return ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5';
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.