Make an dynamically calculator

160 views Asked by At

i want to make an calculator. my code till now is.

            string input;
            input = Console.ReadLine();
            List<string> numbers = new List<string>();

            string curNumber = "";

            foreach (char c in input)
            {
               if (c =='+'|| c =='-'||c =='/'||c =='*')
               {
                   numbers.Add(curNumber);
                   curNumber = "";
               }
               else
               {
                   curNumber += c.ToString();
               }
            }

Now i dont know how i should work furhter with the numbers. If the input is for example: 20+3+13-17. How can i calculate the numbers? How would u implement that logic in my code?

3

There are 3 answers

4
Nissim On BEST ANSWER
var res = new DataTable().Compute("1-2/3*4", null);


edit: Also note you can use the fields in the data table to do functions like summing a column called "Total"

 var Total = DataTable().Compute("Sum(Total)", null);
0
Nissim On

My preferred option will be using NCalc

1
Nissim On

Another option will by using IronPython and IronRuby:

    var res = new IronPython.Hosting.PythonEngine().EvaluateAs<double>("1-2/3*4");