詳細介紹C#數學運算運算式解譯器的範例程式碼

來源:互聯網
上載者:User
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";                    }                }            }        }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.