由于今天在网上搜了一下c#写的计算器,发现大多都太繁琐了,很多没必要并且不容易理解的东西就专门写了这个博客

1.首先新建一个windows窗体应用的项目。执行文件-新建-项目-windows窗体应用

2.在工具箱中拖出一个textbox用于输入和显示,再拖出21个button按钮用来当计算器的按键,在textbox下面还有一个lable控件(我把它属性改成了空格所以看不到了),改一下按钮的text属性

3.双击数字按钮进入代码界面(数字只用一个事件即可,运算符也是用一个事件,其他每个按钮都需要双击添加事件)

4.代码呢已经准备好了,只要双击按钮进入代码界面,然后对应着粘上就行了(注意所有数字都是用的一个事件,都有标注,可以选择按钮,然后单击属性里的事件(闪电图标)查看click的事件)

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 计算器
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}

//定义变量
char oper; double num1; double num2; double result = 0; double memory=0.0;
private void Button9_Click(object sender, EventArgs e)//数字按钮的功能实现 { Button a =
(Button)sender;//判断按下的是哪个按钮 if (textBox1.Text == "0") { textBox1.Text = a.Text;
} else textBox1.Text += a.Text; } private void Button16_Click(object sender,
EventArgs e)//运算符按钮的功能实现 { if (textBox1.Text != "") { num1 =
double.Parse(textBox1.Text); oper = char.Parse(((Button)sender).Text);
textBox1.Text = ""; } } private void Button15_Click(object sender, EventArgs
e)//C按钮的功能实现 { textBox1.Text = ""; textBox1.Focus(); num1 = 0; num2 = 0; oper =
' '; } private void Button14_Click(object sender, EventArgs e)//结果按钮的功能实现 { if
(textBox1.Text != "") { num2 = double.Parse(textBox1.Text); switch (oper) {
case '+': result = num1 + num2; break; case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break; case '÷': if(num2=0) {
MessageBox.Show("0不能为除数!", "提示", MessageBoxButtons.OK,
MessageBoxIcon.Information); break; } result = num1 / num2; break;
textBox1.Text = result.ToString(); } } private void Button17_Click(object
sender, EventArgs e)//小数点按钮的功能实现 { if (textBox1.Text != "") { textBox1.Text +=
"."; } else { textBox1.Text = "0."; } } private void Button18_Click(object
sender, EventArgs e)//M+按钮的功能实现 { if(textBox1.Text!="") { label1.Text = "M";
memory += double.Parse(textBox1.Text); textBox1.Text = " "; } } private void
Button20_Click(object sender, EventArgs e)//MR按钮的功能实现 { textBox1.Text =
memory.ToString(); } private void Button21_Click(object sender, EventArgs
e)//MC按钮的功能实现 { label1.Text = ""; memory = 0; } private void
Button19_Click(object sender, EventArgs e)//M-按钮的功能实现 { if (textBox1.Text !=
"") { label1.Text = "M"; memory -= double.Parse(textBox1.Text); textBox1.Text =
" "; } } }
}

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信