标签:
代码部分:
public partial class 计算器 : Form { public 计算器() { InitializeComponent(); } private double sum = 0;//存放运算结果 private string biaodashi="";//用于存放除了刚点过的运算符的前面表达式部分 private string preyunsuanfu="";//用来存放上一步运算符,用于下次点运算符的时候算上一步的结果 private bool isok = false;//用它记录是否是刚开始运行程序,是否刚刚点过运算符 private void one_Click(object sender, EventArgs e) { Button btn = (Button)sender; if (!isok||textshu.Text=="0")//如果isok是false或者输入框是0那就清空 textshu.Text = btn.Text; else//否则就累加 textshu.Text += btn.Text; isok = true;//凡是点完数字就设置isok为true } private void jia_Click(object sender, EventArgs e) { Button btn = (Button)sender; if (isok) { if (biaodashi == "" && preyunsuanfu == "")//第一次点运算符 { sum = double.Parse(textshu.Text); biaodashi = textshu.Text; } else//不是第一次点运算,先算上一步运算 { if (preyunsuanfu == "+") { sum = sum + double.Parse(textshu.Text); } if (preyunsuanfu == "-") { sum = sum - double.Parse(textshu.Text); } if (preyunsuanfu == "*") { sum = sum * double.Parse(textshu.Text); } if (preyunsuanfu == "/") { sum = sum / double.Parse(textshu.Text); } if (preyunsuanfu == "%") { sum = sum % double.Parse(textshu.Text); } biaodashi = biaodashi + preyunsuanfu + textshu.Text; } } txtbiaodashi.Text = biaodashi + btn.Text;//把表达式文本框拼接显示 preyunsuanfu = btn.Text;//换上一步运算符,将刚才点的运算符,存为上一步运算符 textshu.Text = sum.ToString();//将下面输入框显示为运算结果 isok = false;//记录刚刚点过的运算符,以便点数字的时候知道是刚点了运算符 } private void clear_Click(object sender, EventArgs e) { isok = false; biaodashi = ""; textshu.Text = "0"; txtbiaodashi.Text = ""; preyunsuanfu = ""; sum = 0; } private void shan_Click(object sender, EventArgs e) { if (textshu.Text.Length > 1) { textshu.Text = textshu.Text.Substring(0, textshu.Text.Length - 1); } else { textshu.Text = "0"; } } private void dian_Click(object sender, EventArgs e) { if (isok) { if (!textshu.Text.Contains(".")) { textshu.Text += "."; } } else { textshu.Text = "0."; } } private void dengyu_Click(object sender, EventArgs e) { if (preyunsuanfu == "+") { sum = sum + double.Parse(textshu.Text); } if (preyunsuanfu == "-") { sum = sum - double.Parse(textshu.Text); } if (preyunsuanfu == "*") { sum = sum * double.Parse(textshu.Text); } if (preyunsuanfu == "/") { sum = sum / double.Parse(textshu.Text); } if (preyunsuanfu == "%") { sum = sum % double.Parse(textshu.Text); } biaodashi = ""; preyunsuanfu = ""; txtbiaodashi.Text = ""; textshu.Text = sum.ToString(); isok = false; } }
效果如下:
标签:
原文地址:http://www.cnblogs.com/xuankai1987/p/5084324.html