C#Form窗体写一个计算器(初级版)
样子如上图所示,代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculator1
{
public partial class Form1 : Form
{
float result;
string a, b;
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)//加
{
a = txtNum1.Text;//a和b用来存放两个txtbox的内容,即两个数
b = txtNum2.Text;
float Number1 = float.Parse(a);//将字符串转换成数值,float类型,分别存放到Number1和Number2中。
//为什么要转换?因为我们要计算数值相加减乘除后的结果
float Number2 = float.Parse(b);
result = Number1 + Number2;//计算结果
txtResult.Text=result.ToString();
}
private void btnSub_Click(object sender, EventArgs e)//减
{
a = txtNum1.Text;
b = txtNum2.Text;
float Number1 = float.Parse(a);
float Number2 = float.Parse(b);
result = Number1 - Number2;
txtResult.Text=result.ToString();
}
private void btnMul_Click(object sender, EventArgs e)//乘
{
a = txtNum1.Text;
b = txtNum2.Text;
float Number1 = float.Parse(a);
float Number2 = float.Parse(b);
result = Number1 * Number2;
txtResult.Text=result.ToString();
}
private void btnDiv_Click(object sender, EventArgs e)//除
{
a = txtNum1.Text;
b = txtNum2.Text;
float Number1 = float.Parse(a);
float Number2 = float.Parse(b);
result = Number1 / Number2;
txtResult.Text=result.ToString();
}
}
}