ide图片如下(模仿的iphone的简易计算器)
首先设置变量:
double num1, num2;
string f;
int flag = 0;
flag是计算之后清除结果的按键,比如2*3=6,最终显示结果为6,此时将flag设为1表明当前为结果显示,如果想要重新输入的话,且当前是上一步的结果显示,需要将结果显示清除掉。
对于1-9按键功能:
private void buttonone_Click(object sender, EventArgs e)
{
Button a = (Button)sender;
if (this.textBox1.Text == "error!") this.textBox1.Text = "";
if (this.textBox1.Text == "" && a.Text == ".") return;
if(flag==1)
{
this.textBox1.Text = "";
flag = 0;
}
this.textBox1.Text += a.Text;
}
第一个if语句是报错的时候记得清除
第二个if语句是 符号“. ”前面必须有数字才行。
运算部分的话:
private void buttonequal_Click(object sender, EventArgs e)
{
num2 = double.Parse(this.textBox1.Text);
if (f == "+")
{
this.textBox1.Text = (num1 + num2).ToString();
}
if (f == "-")
{
this.textBox1.Text = (num1 - num2).ToString();
}
if (f == "*")
{
this.textBox1.Text = (num1 * num2).ToString();
}
if (f == "/")
{ if (num2 == 0.0) this.textBox1.Text = "error!";
else this.textBox1.Text = (num1 / num2).ToString();
}
flag = 1;
}
清除部分:
private void button1_Click(object sender, EventArgs e)
{
this.textBox1.Clear();
}
存储运算符部分:
private void buttondivision_Click(object sender, EventArgs e)
{
num1 = double.Parse(this.textBox1.Text);
this.textBox1.Text = "";
Button b = (Button)sender;
f = b.Text;
}
这里名字仅仅包含除法,其实包括了加减乘除。
百分号运算和正负运算:
private void button3_Click(object sender, EventArgs e)
{
double num3 = double.Parse(this.textBox1.Text);
num3 = num3/100;
this.textBox1.Text = num3.ToString();
}
private void buttonnp_Click(object sender, EventArgs e)
{
double num3= double.Parse(this.textBox1.Text);
num3 = -num3;
this.textBox1.Text = num3.ToString();
}