程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#數學運算表達式解釋器

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);  
        }  
    }  
}

URL:http://www.bianceng.cn/Programming/csharp/201410/45774.htm

分析一行表達式:

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#數學運算表達式解釋器源碼

http://download.csdn.net/detail/testcs_dn/7635269

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved