用C#语言写一个计算器
第一步、创建一个Windows窗体,
第二步、创建样式,在工具箱中找到TextBox和Button。
第三步、排版按钮的位置和跟改名字
结果:
Button |
TextBox |
就这样排版,然后我们双击按钮,写实现功能代码。
我们先给0-9和.取值
代码是: private void button5_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "1";//取值 }
private void button6_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "2";//取值 }
private void button7_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "3";//取值 }
private void button9_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "4";//取值 }
private void button10_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "5";//取值 }
private void button11_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "6";//取值 }
private void button13_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "7";//取值 }
private void button14_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "8";//取值 }
private void button15_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "9";//取值 }
private void button2_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "0"; }
private void button3_Click(object sender, EventArgs e)
{ textBox1.Text = textBox1.Text + "."; }
如果+、-、*、/、%要取到结果,那么我们要字符串保存到变量里
代码是
public double jisuan1; //定义一个变量值
public double jisuan2; //定义一个变量值
public char fuhao; //定义一个变量值
public double jiegun = 0; //定义一个变量值
private void button8_Click(object sender, EventArgs e)
{
jisuan1 = Convert.ToDouble(textBox1.Text);
fuhao = '+';
textBox1.Text = "";
}
private void button12_Click(object sender, EventArgs e)
{
jisuan1 = Convert.ToDouble(textBox1.Text);
fuhao = '-';
textBox1.Text = "";
}
private void button16_Click(object sender, EventArgs e)
{jisuan1 = Convert.ToDouble(textBox1.Text);
fuhao = '*';
textBox1.Text = "";}
private void button20_Click(object sender, EventArgs e)
{jisuan1 = Convert.ToDouble(textBox1.Text);
fuhao = '/';
textBox1.Text = "";}
private void button21_Click(object sender, EventArgs e)
{jisuan1 = Convert.ToDouble(textBox1.Text);
fuhao ='%';
textBox1.Text = "";}
= 结果的代码和其他代码不一样,利用变量来得到运算结果
代码是 private void button4_Click(object sender, EventArgs e)//运算代码
{
jisuan2 = Convert.ToDouble(textBox1.Text);
switch (fuhao)
{
case '+':
jiegun = jisuan1 + jisuan2;
break;
case '-':
jiegun = jisuan1 - jisuan2;
break;
case '*':
jiegun = jisuan1 * jisuan2;
break;
case '/':
jiegun = jisuan1 / jisuan2;
break;
case '%':
jiegun = jisuan1 / jisuan2;
break;
}
textBox1.Text = Convert.ToString(jiegun);
}
最后就是CE,意思是为清空。清空的代码为
private void button17_Click(object sender, EventArgs e)
{
textBox1.Text = "";