1 namespace WindowsFormsApplication6 2 { 3 public partial class Form1 : Form 4 { 5 //存储上次点击了什么按钮,0代表什么都没有点击,1代表数字按钮,2代表点击了运算符 6 private int prev = 0; 7 //存储计算的中间结果 8 private decimal zjjg = 0; 9 //记录上次按得什么运算符 10 private string prevysf = "+"; 11 12 public Form1() 13 { 14 InitializeComponent(); 15 } 16 17 private void button1_Click(object sender, EventArgs e) //输入的数 18 { 19 //将事件源转换为按钮 20 Button btn = sender as Button; 21 //替换(文本框内容为0,点击了运算符) 22 if (prev == 2 || txtbottom.Text == "0") 23 { 24 txtbottom.Text = btn.Text; 25 } 26 //追加(内容不为0,并且上次没有点击运算符) 27 else 28 { 29 txtbottom.Text += btn.Text; 30 } 31 //点击了按钮数字 32 prev = 1; 33 } 34 35 private void button4_Click(object sender, EventArgs e) //加减乘除 36 { 37 //事件源转换为按钮 38 Button btn = sender as Button; 39 //上次按了数字 40 if (prev == 1) 41 { 42 txttop.Text += txtbottom.Text + btn.Text;//进行显示拼接 43 switch (prevysf) 44 { 45 case "+": 46 zjjg = zjjg + Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 47 break; 48 case "-": 49 zjjg = zjjg - Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 50 break; 51 case "*": 52 zjjg = zjjg * Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 53 break; 54 case "/": 55 zjjg = zjjg / Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 56 break; 57 } 58 59 txtbottom.Text = zjjg.ToString(); 60 } 61 //上次按了运算符 62 else 63 { 64 65 if (txttop.Text != "") 66 { 67 string s = txttop.Text; 68 s = s.Substring(0, s.Length - 1); 69 s = s + btn.Text; 70 txttop.Text = s; 71 } 72 else 73 { 74 75 txttop.Text = txtbottom.Text + btn.Text; 76 } 77 } 78 //点击了运算符 79 prev = 2; 80 //记录下运算符 81 prevysf = btn.Text; 82 } 83 84 private void button9_Click(object sender, EventArgs e) //清空 85 { 86 txttop.Text = ""; 87 txtbottom.Text = "0"; 88 prevysf = "+"; 89 prev = 0; 90 zjjg = 0; 91 } 92 93 private void button11_Click(object sender, EventArgs e) //等于 94 { 95 //事件源转换为按钮 96 Button btn = sender as Button; 97 switch (prevysf) 98 { 99 case "+": 100 zjjg = zjjg + Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 101 break; 102 case "-": 103 zjjg = zjjg - Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 104 break; 105 case "*": 106 zjjg = zjjg * Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 107 break; 108 case "/": 109 zjjg = zjjg / Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果 110 break; 111 } 112 txtbottom.Text = zjjg.ToString(); 113 txttop.Text = ""; 114 prevysf = ""; 115 prev = 2; 116 } 117 118 private void button17_Click(object sender, EventArgs e) //回退一个 119 { 120 string s = txtbottom.Text; 121 if (s.Length >1) 122 { 123 s = s.Substring(0, s.Length - 1); 124 txtbottom.Text = s; 125 } 126 else if(s.Length==1) 127 { 128 txtbottom.Text = "0"; 129 } 130 } 131 132 private void Form1_Load(object sender, EventArgs e) 133 { 134 135 } 136 } 137 }