1

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

Edited by bisiii: n/a

3
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by ddanbe
-1

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

Edited by Mitja Bonca: n/a

0

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.

1

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';
        }
    }
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.