效果圖:

代碼區:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { //存儲上次點擊了什么按鈕,0代表什么都沒點擊,1代表點擊了數字按鈕,2代表點擊了運算符 private int prev = 0; //存儲計算的中間結果 private decimal zj = 0; //記錄上次按的什么運算符 private string prevysf = "+"; public Form1() { InitializeComponent(); } //數字鍵按鈕 private void button8_Click(object sender, EventArgs e) { //將事件源轉換為按鈕 Button btn = sender as Button; //替換(如果下面文本框內容為0或者上次點擊了運算符) if (prev == 2 || txtbottom.Text == "0") { txtbottom.Text = btn.Text; } //追加(如果下面文本框內容不為0並且上次沒有點擊運算符) else { txtbottom.Text += btn.Text; } //點擊了數字按鈕 prev = 1; } //運算符按鈕 private void button17_Click(object sender, EventArgs e) { Button btn = sender as Button; //上次按了數字 if (prev == 1) { txttop.Text += txtbottom.Text + btn.Text; switch (prevysf) { case "+": zj = zj + Convert.ToDecimal(txtbottom.Text); break; case "-": zj = zj - Convert.ToDecimal(txtbottom.Text); break; case "*": zj = zj * Convert.ToDecimal(txtbottom.Text); break; case "/": zj = zj / Convert.ToDecimal(txtbottom.Text); break; } txtbottom.Text = zj.ToString(); } //上次按了運算符 else { string s = txttop.Text; s = s.Substring(0, s.Length - 1); s = s + btn.Text; txttop.Text = s; } //點擊了運算符 prev = 2; //記錄下運算符 prevysf = btn.Text; } //清零按鈕 private void button19_Click(object sender, EventArgs e) { txttop.Text = ""; txtbottom.Text = "0"; prev = 0; zj = 0; prevysf = "+"; } private void button20_Click(object sender, EventArgs e) { txtbottom.Text = "0"; } //等號按鈕 private void button4_Click(object sender, EventArgs e) { Button btn = sender as Button; txttop.Text += txtbottom.Text + btn.Text; switch (prevysf) { case "+": zj = zj + Convert.ToDecimal(txtbottom.Text); break; case "-": zj = zj - Convert.ToDecimal(txtbottom.Text); break; case "*": zj = zj * Convert.ToDecimal(txtbottom.Text); break; case "/": zj = zj / Convert.ToDecimal(txtbottom.Text); break; } txtbottom.Text = zj.ToString(); txttop.Text = ""; zj = 0; } //點 private void button3_Click(object sender, EventArgs e) { txtbottom.Text += "."; } } }
