WinForm 制作一个简单的计算器

 namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
//存储上次点击了什么按钮,0代表什么都没有点击,1代表数字按钮,2代表点击了运算符
private int prev = ;
//存储计算的中间结果
private decimal zjjg = ;
//记录上次按得什么运算符
private string prevysf = "+"; public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e) //输入的数
{
//将事件源转换为按钮
Button btn = sender as Button;
//替换(文本框内容为0,点击了运算符)
if (prev == || txtbottom.Text == "")
{
txtbottom.Text = btn.Text;
}
//追加(内容不为0,并且上次没有点击运算符)
else
{
txtbottom.Text += btn.Text;
}
//点击了按钮数字
prev = ;
} private void button4_Click(object sender, EventArgs e) //加减乘除
{
//事件源转换为按钮
Button btn = sender as Button;
//上次按了数字
if (prev == )
{
txttop.Text += txtbottom.Text + btn.Text;//进行显示拼接
switch (prevysf)
{
case "+":
zjjg = zjjg + Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
case "-":
zjjg = zjjg - Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
case "*":
zjjg = zjjg * Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
case "/":
zjjg = zjjg / Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
} txtbottom.Text = zjjg.ToString();
}
//上次按了运算符
else
{ if (txttop.Text != "")
{
string s = txttop.Text;
s = s.Substring(, s.Length - );
s = s + btn.Text;
txttop.Text = s;
}
else
{ txttop.Text = txtbottom.Text + btn.Text;
}
}
//点击了运算符
prev = ;
//记录下运算符
prevysf = btn.Text;
} private void button9_Click(object sender, EventArgs e) //清空
{
txttop.Text = "";
txtbottom.Text = "";
prevysf = "+";
prev = ;
zjjg = ;
} private void button11_Click(object sender, EventArgs e) //等于
{
//事件源转换为按钮
Button btn = sender as Button;
switch (prevysf)
{
case "+":
zjjg = zjjg + Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
case "-":
zjjg = zjjg - Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
case "*":
zjjg = zjjg * Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
case "/":
zjjg = zjjg / Convert.ToDecimal(txtbottom.Text); //计算上次运行的结果
break;
}
txtbottom.Text = zjjg.ToString();
txttop.Text = "";
prevysf = "";
prev = ;
} private void button17_Click(object sender, EventArgs e) //回退一个
{
string s = txtbottom.Text;
if (s.Length >)
{
s = s.Substring(, s.Length - );
txtbottom.Text = s;
}
else if(s.Length==)
{
txtbottom.Text = "";
}
} private void Form1_Load(object sender, EventArgs e)
{ }
}
}
上一篇:murri


下一篇:拾人牙慧,浅记一些C++的类