C# Case_4 简易计算器
Form设计:

三个textBox,一个comboBox,一个button
修改第一个textBox的属性,将Name修改为textNumber1,第二个textBox的Name修改为textNumber2,第三个textBox的Name修改为textResult
右键选中下拉框—编辑项,添加 + - * / 四个运算符
设置button1的Text属性为 =
添加新的类Calculator.cs
namespace 简易计算器 { class Calculator { public double NumberOne { get; set; } public double NumberTwo { get; set; } public double Add() { return NumberOne + NumberTwo; } public double Sub() { return NumberOne - NumberTwo; } public double Mul() { return NumberOne * NumberTwo; } public double Div() { return NumberOne / NumberTwo; } } }
双击Form1窗体,添加以下代码:
/// <summary> /// 程序加载的时候,将下拉框的第一项显示到下拉框列表中 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { //让下拉框列表中默认被选中的项的索引为0 comboBox1.SelectedIndex = 0; }
双击button1,添加以下代码:
/// <summary> /// 计算 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //获得用户在文本框中输入的内容 string strNumberOne = textNumber1.Text.Trim(); string strNumberTwo = textNumber2.Text.Trim(); //将它们转换成double类型 double d1 = Convert.ToDouble(strNumberOne); double d2 = Convert.ToDouble(strNumberTwo); //创建计算类的实例 Calculator cal = new Calculator(); //将两个数字赋值给这个对象的两个属性 cal.NumberOne = d1; cal.NumberTwo = d2; //获得用户在下拉框中选择的操作符 string oper = comboBox1.SelectedItem.ToString(); switch (oper) { case "+": textResult.Text=cal.Add().ToString(); break; case "-": textResult.Text = cal.Sub().ToString(); break; case "*": textResult.Text = cal.Mul().ToString(); break; case "/": textResult.Text = cal.Div().ToString(); break; default: MessageBox.Show("请选择正确的操作符"); break; } }
运行结果:




浙公网安备 33010602011771号