习题10:参照Windows系统“附件”中的“计算器”,自行编写一个简易的计算器。要求:可以实现由0~4构成的整数的加减运算。

参照Windows系统“附件”中的“计算器”,自行编写一个简易的计算器。要求:可以实现由0~4构成的整数的加减运算。

 

【解答】

 

 

1) 窗体界面如图Ex5-5-2所示;

习题10:参照Windows系统“附件”中的“计算器”,自行编写一个简易的计算器。要求:可以实现由0~4构成的整数的加减运算。_第1张图片

2) 将InputNumber事件作为button0、button1、button2、button3、button4的Click事件。

完整代码如下:

 

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Exer2 { public partial class FormCalculator : Form { enum calculateType { none, add, sub }; calculateType myCal = calculateType.none; int x, y; bool isY = false; public FormCalculator() { InitializeComponent(); textBox.TextAlign = HorizontalAlignment.Right; } private void InputNumber(object sender, EventArgs e) { Button num = (Button)sender; if (isY) { textBox.Clear(); isY = false; } textBox.Text += num.Text; } private void buttonEqual_Click(object sender, EventArgs e) { y = Convert.ToInt32(textBox.Text); if (myCal == calculateType.add) { textBox.Text = Convert.ToString(x + y); myCal = calculateType.none; } if (myCal == calculateType.sub) { textBox.Text = Convert.ToString(x - y); myCal = calculateType.none; } isY = true; } private void addButton_Click(object sender, EventArgs e) { myCal = calculateType.add; x = Convert.ToInt32(textBox.Text); isY = true; } private void buttonSub_Click(object sender, EventArgs e) { myCal = calculateType.sub; x = Convert.ToInt32(textBox.Text); isY = true; } private void buttonClear_Click(object sender, EventArgs e) { textBox.Text = ""; myCal = calculateType.none; isY = false; } } } 

 

 

你可能感兴趣的:(开发练习题)