c#编写简单计算器

刚接触c#,依照惯例,写个简单的计算器,只写了加法,乘法,其他的类似,编辑器用的vs2008

首先打开vs ,新建c#的Windows窗体应用程序,接下来的项目的名称是WindowsFormsApplication2,不是WindowsFormsApplication3。

然后设计计算器的ui界面,比较简单,请谅解。。。

接下来就是编码,首先要给按钮增加点击事件,代码如下:

button1.Click += new EventHandler(Btns_Click);
button2.Click += new EventHandler(Btns_Click);

但是这两行代码不能单独放在代码里,需要放在一个方法里面;

private void addOperatorBtns()
{

button1.Click += new EventHandler(Btns_Click);
button2.Click += new EventHandler(Btns_Click);

}

然后还要声明该方法:

private void Form1_Load(object sender, EventArgs e)
{
addOperatorBtns();
}

接下来就是该点击事件方法的代码实现:

private void Btns_Click(object sender, EventArgs e) //按钮Click事件
{

Button m_CurBtn = (Button)sender;
switch (m_CurBtn.Name)
{
case "button1":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a + b;

textBox3.Text = c+" "; 
break;
}
case "button2":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a * b;

textBox3.Text = c + " "; 
break;
}

}

}

 

最后 Form1.cs里面的全部代码如下:

   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{

double a = 0;
double b = 0;
double c = 0;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
addOperatorBtns();
}

private void label1_Click(object sender, EventArgs e)
{

}

private void addOperatorBtns()
{

button1.Click += new EventHandler(Btns_Click);
button2.Click += new EventHandler(Btns_Click);

}

private void Btns_Click(object sender, EventArgs e) //按钮Click事件
{

Button m_CurBtn = (Button)sender;
switch (m_CurBtn.Name)
{
case "button1":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a + b;

textBox3.Text = c+" "; 
break;
}
case "button2":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a * b;

textBox3.Text = c + " "; 
break;
}

}

}

private void button2_Click(object sender, EventArgs e)
{

}

 

 

}
}

 

转载于:https://www.cnblogs.com/yalong/p/5674350.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值