码迷,mamicode.com
首页 > 其他好文 > 详细

C#数学运算表达式解释器

时间:2014-07-15 22:16:27      阅读:390      评论:0      收藏:0      [点我收藏+]

标签:c#   数学   运算   表达式   解释器   

C#数学运算表达式解释器

bubuko.com,布布扣

测试文件内容:

a=2+3*2;
b=2*(2+3);
浏览按钮事件处理程序:

        private void button_browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fbd = new OpenFileDialog();
            fbd.Title = "请选择一个文件:";
            fbd.CheckFileExists = true;
            fbd.CheckPathExists = true;
            fbd.Filter = "*.txt(文本文件)|*.txt|*.*(所有文件)|*.*";
            fbd.FileName = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox_saveDir.Text = fbd.FileName;
                try
                {
                    FileStream fs = new FileStream(fbd.FileName, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        analyse(line);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message + "\r\n堆栈:" + ex.StackTrace);
                }
            }
        }
分析一行表达式:

        private void analyse(string line)
        {
            //以分号作为结束符,支持一行内写多个语句
            string[] expA = line.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < expA.Length; i++)
            {
                analyseExpA(expA[i]);
            }
        }
计算一条表达式:
        private void analyseExpA(string expA)
        {
            string[] expB = expA.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < expB.Length; i++ )
            {
                Regex reg = new Regex("[a-zA-Z]");
                if (!reg.IsMatch(expB[i]))
                {
                    object obj = EvalExpress(expB[i]);
                    if (obj != null)
                    {
                        textBox1.Text += expA + " = " + obj.ToString() + "\r\n";
                    }
                    else
                    {
                        textBox1.Text += expA + ",无法识别的表达式\r\n";
                    }
                }
            }
        }

源码下载:C#数学运算表达式解释器源码

C#数学运算表达式解释器,布布扣,bubuko.com

C#数学运算表达式解释器

标签:c#   数学   运算   表达式   解释器   

原文地址:http://blog.csdn.net/testcs_dn/article/details/37776937

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!