本文实例为大家分享了C#实现简易计算器小功能的具体代码,供大家参考,具体内容如下
简易的登陆界面。
具有幻灯片效果。(picturebox time控件)
计算器支持多位数,小数,括号的运算。
音乐是一个练习用的小控件(Listbox),可以选择指定的歌曲播放,直接忽略掉吧。
建立winform窗体
数字和运算符都为button,输入和输出的为textbox
基本代码
在所有button控件的click事件均为加上所对应的文本。
例如:数字1所对应的button就为
1
|
textBox1.Text += '1' ; |
运算符同理
1
|
textBox1.Text += '*' ; |
核心代码
核心代码均在‘=’的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
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
|
Stack< double > vs = new Stack< double >(); //运算符栈 Stack< char > vvs = new Stack< char >(); //操作符栈 string a = textBox1.Text + '=' ; string b = "" ; vvs.Push( '=' ); for ( int i = 0; i < a.Length; i++) { if (a[i] >= '0' && a[i] <= '9' ||a[i]== '.' ) { b += a[i]; } else if (a[i] == '=' ) { if (b != "" ) vs.Push(Convert.ToDouble(b)); while (vvs.Peek() != '=' ) { char t = vvs.Pop(); double d = vs.Pop(); if (vs.Count() != 0) { double j = vs.Pop(); vs.Push(Jisuan(d, t, j)); } else { MessageBox.Show( "你输入的有问题" ); textBox1.Text = "" ; } } } else { if (b != "" ) vs.Push(Convert.ToDouble(b)); switch (Bijiao(vvs.Peek(), a[i])) { case '>' : while (vvs.Count != 1 && vvs.Peek() != '(' ) { char th = vvs.Pop(); double f = vs.Pop(); double g = vs.Pop(); vs.Push(Jisuan(f, th, g)); } if (vvs.Peek() == '(' && a[i] == ')' ) { vvs.Pop(); } else { vvs.Push(a[i]); } break ; case '<' : vvs.Push(a[i]); break ; case '=' : while (vvs.Peek() != '=' ) { char th = vvs.Pop(); double f = vs.Pop(); double g = vs.Pop(); vs.Push(Jisuan(f, th, g)); } break ; } b = "" ; } } textBox1.Text = "" ; if (vs.Count()!=0) { textBox1.Text = vs.Peek().ToString(); } } |
所用到的方法(函数)
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
|
public double Jisuan( double c, char t, double a) //用来计算的方法 { switch (t) { case '+' : return a + c; case '-' : return a - c; case '*' : return a * c; case '/' : if (c == 0) { MessageBox.Show( "0不能作为被除数" ); return 0; } else return a / c; case '%' : return a % c; default : return 0; } } char Bijiao( char theta1, char theta2) //比较运算符优先级的方法 { if ((theta1 == '(' && theta2 == ')' ) || (theta1 == '#' && theta2 == '#' )) { return '=' ; } else if (theta1 == '(' || theta1 == '#' || theta2 == '(' || (theta1 == '+' || theta1 == '-' ) && (theta2 == '*' || theta2 == '/' )) { return '<' ; } else return '>' ; } |
为了使计算器更加美观,可以添加picturebox控件等等。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_43920680/article/details/89003595