您当前的位置: 首页 >  数学

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

发布时间:2014-07-14 23:39:00 ,浏览量:0

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

测试文件内容:

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#数学运算表达式解释器源码

关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    108291博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0478s