Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C#

Inside the Mathematical Expressions Evaluator

Rate me:
Please Sign up or sign in to vote.
4.88/5 (43 votes)
17 Jan 2008CPOL8 min read 115.7K   3.4K   77  
An article on mathematical expression evaluation
using System;
using System.Collections.Generic;
using System.Text;

namespace SevenZ.Calculator
{
   public partial class Calculator
   {
      public delegate void CalcVariableDelegate(object sender, EventArgs e);
      public event CalcVariableDelegate OnVariableStore;

      Dictionary<string, double> variables;

      public const string AnswerVar = "r";

      private void LoadConstants()
      {
         variables = new Dictionary<string, double>();
         variables.Add("pi", Math.PI);
         variables.Add("e", Math.E);
         variables.Add(AnswerVar, 0);

         if (OnVariableStore != null)
            OnVariableStore(this, new EventArgs());
      }

      public Dictionary<string, double> Variables
      {
         get { return variables; }
      }

      public void SetVariable(string name, double val)
      {
         if (variables.ContainsKey(name))
            variables[name] = val;
         else
            variables.Add(name, val);

         if (OnVariableStore != null)
            OnVariableStore(this, new EventArgs());
      }

      public double GetVariable(string name)
      {  // return variable's value // if variable ha push default value, 0
         return variables.ContainsKey(name) ? variables[name] : 0;                    
      }
   }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Finland Finland
I'm a Master degree student, studying at the University of Joensuu, Finland.

Comments and Discussions