用C# WinForm寫的一個簡單的計算器程式(可以輸入複雜的表示式),歡迎大家指出Bug
阿新 • • 發佈:2019-02-01
本人是初學者,剛看到WinForm程式設計這一章,便自己動手寫了一個計算器的程式當做練習。網上查過的大多數資料都說到了用逆波蘭式計算,但是我試了下不太會,就用了自己的方法寫了下試試,發現居然能用。
下面是介面截圖:
(Expression:可以滑鼠點選輸入計算式,也可以直接貼上進去)
(clear可以清除表示式,Backspace能刪除表示式的最後一位)
以下是計算部分原始碼,程式碼比較冗餘,沒來得及修改
// ----------------------------------------------------------------------- // <copyright file="Calculate.cs" company=""> // TODO: Update copyright text. // </copyright> // ----------------------------------------------------------------------- using System.Collections; namespace WinFormSamples { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; /// <summary> /// TODO: Update summary. /// </summary> public class Calculate { public string GetResult(string str) { str = str + "+"; char[] expArry = str.ToCharArray(); string operations="()+-*/"; Hashtable signs =new Hashtable(); string[] numArry = str.Split('(',')','+','-','*','/'); //分割字串,提取表示式中的數字 //定義操作符的優先順序並存入雜湊表 signs.Add("(",0); signs.Add(")",0); signs.Add("+",1); signs.Add("-",1); signs.Add("*",2); signs.Add("/",2); string[] resultArry = new string[99]; int resultIndex = 0; int numIndex = 0; for (int i = 0; i < str.Length - 1; i++) { if (operations.Contains(expArry[i])) { //遇到符號直接存入resultArry resultArry[resultIndex] = expArry[i].ToString(); resultIndex++; } else if (operations.Contains(expArry[i + 1])) { //連續非符號字元,從numArry取出一個元素放入resultArry while (numArry[numIndex] == "") //去除numArry中的空元素 { numIndex++; } resultArry[resultIndex] = numArry[numIndex]; numIndex++; resultIndex++; } } Stack<char> sign_stack = new Stack<char>();//定義符號棧 Stack<string> num_stack = new Stack<string>();//定義運算元棧 char calc_sign; try { for (int i = 0; i < resultIndex + 1; i++) { if (i == resultIndex) { if (sign_stack.Count != 0) { calc_sign = sign_stack.Pop(); Calc(ref sign_stack, ref num_stack,ref resultArry[i],ref calc_sign); while (num_stack.Count() > 1) //計算到棧中只剩一個運算元為止 { calc_sign = sign_stack.Pop(); Calc(ref sign_stack, ref num_stack, ref resultArry[i], ref calc_sign); } } } else if (operations.Contains(resultArry[i])) { if (resultArry[i] != "(") { if (sign_stack.Count() == 0 || Convert.ToInt32(signs[resultArry[i]]) > Convert.ToInt32(signs[sign_stack.Peek().ToString()])) //第一個操作符或者當前操作符優先順序大於符號棧棧頂元素時,當前操作符入棧 { sign_stack.Push(resultArry[i].ToCharArray()[0]); } else { //否則,符號棧出棧操作符,數字棧出棧兩個運算元進行運算 calc_sign = sign_stack.Pop(); Calc(ref sign_stack, ref num_stack,ref resultArry[i],ref calc_sign); } } else { sign_stack.Push(resultArry[i].ToCharArray()[0]); } } else { num_stack.Push(resultArry[i]); } } //結果出棧 return num_stack.Pop(); } catch (Exception e) { MessageBox.Show("表示式格式不正確,請檢查! "+e.Message); return null; } } public string CalculateResult(string num1, string num2, char sign) { double result = 0; double oper_num1=Convert.ToDouble(num1); double oper_num2=Convert.ToDouble(num2); if (sign.ToString()=="+") { result = oper_num1 + oper_num2; } if (sign.ToString() == "-") { result = oper_num1 - oper_num2; } if (sign.ToString() == "*") { result = oper_num1 * oper_num2; } if (sign.ToString() == "/") { if(oper_num2!=0) result = oper_num1 / oper_num2; else MessageBox.Show("表示式中有除0操作,請檢查!"); } return result.ToString(); } public void Calc(ref Stack<char> sign, ref Stack<string> num, ref string str, ref char calc_sign) { string num1 = ""; string num2 = ""; if (str == ")") { while (calc_sign != '(') { num2 = num.Pop(); num1 = num.Pop(); num.Push(CalculateResult(num1, num2, calc_sign)); calc_sign = sign.Pop(); } } else { num2 = num.Pop(); num1 = num.Pop(); num.Push(CalculateResult(num1, num2, calc_sign)); if (str!=null&&"()+-*/".Contains(str)) { sign.Push(str.ToCharArray()[0]); } } } } }
下面是窗體程式:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinFormSamples { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { textBox1.Text += "1"; } private void button2_Click(object sender, EventArgs e) { textBox1.Text += "2"; } private void button3_Click(object sender, EventArgs e) { textBox1.Text += "3"; } private void button4_Click(object sender, EventArgs e) { textBox1.Text += "4"; } private void button5_Click(object sender, EventArgs e) { textBox1.Text += "5"; } private void button6_Click(object sender, EventArgs e) { textBox1.Text += "6"; } private void button7_Click(object sender, EventArgs e) { textBox1.Text += "7"; } private void button8_Click(object sender, EventArgs e) { textBox1.Text += "8"; } private void button9_Click(object sender, EventArgs e) { textBox1.Text += "9"; } private void button10_Click(object sender, EventArgs e) { textBox1.Text += "0"; } private void button11_Click(object sender, EventArgs e) { textBox1.Text += "*"; } private void button12_Click(object sender, EventArgs e) { textBox1.Text += "."; } private void button13_Click(object sender, EventArgs e) { textBox1.Text += "+"; } private void button14_Click(object sender, EventArgs e) { textBox1.Text += "-"; } private void button15_Click(object sender, EventArgs e) { textBox1.Text += "/"; } private void button16_Click(object sender, EventArgs e) { Calculate calculate = new Calculate(); textBox2.Text = calculate.GetResult(textBox1.Text); } private void button17_Click(object sender, EventArgs e) { textBox1.Text = ""; textBox2.Text = ""; } private void button18_Click(object sender, EventArgs e) { textBox1.Text += "("; } private void button19_Click(object sender, EventArgs e) { textBox1.Text += ")"; } private void button20_Click(object sender, EventArgs e) { textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length-1,1); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("chrome.exe", "http://msdn.microsoft.com/zh-cn/default.aspx"); } } }