欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

详细介绍C#数学运算表达式解释器的示例代码

程序员文章站 2022-05-16 21:33:41
...
C#数学运算表达式解释器

详细介绍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#数学运算表达式解释器的示例代码的详细内容,更多请关注其它相关文章!