我是靠谱客的博主 傻傻啤酒,这篇文章主要介绍用c#实现简易的计算器功能实例代码,现在分享给大家,希望可以做个参考。

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

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

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

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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; }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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 '÷': 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 = " "; } } }

以上所述是小编给大家介绍的c#实现简易的计算器功能详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对靠谱客网站的支持!

最后

以上就是傻傻啤酒最近收集整理的关于用c#实现简易的计算器功能实例代码的全部内容,更多相关用c#实现简易内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(124)

评论列表共有 0 条评论

立即
投稿
返回
顶部