用C#做一个计算器,要求加减乘除用combobox来做,有计算即可。 回答时请附上代码(及说明)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.comboBox1.SelectedIndex = 0;
}
//计算结果
private void button1_Click(object sender, EventArgs e)
{
//输入的数不能为空
if (this.textBox1.Text == "")
{
MessageBox.Show("请输入第一个数!");
return;
}
else if (this.textBox2.Text == "")
{
MessageBox.Show("请输入第二个数!");
return;
}
//输入的数必须为数字
Regex r = new Regex("^[0123456789]+$");
if (!r.Match(this.textBox1.Text).Success || !r.Match(this.textBox2.Text).Success)
{
MessageBox.Show("请输入数字!");
return;
}
//获取用户输入的数
int num1 = int.Parse(this.textBox1.Text);
int num2 = int.Parse(this.textBox2.Text);
int reasult = 0;//默认结果为0
//匹配运算符
switch (this.comboBox1.Text)
{
case "+":
reasult = num1 + num2;
break;
case "-":
reasult = num1 - num2;
break;
case "*":
reasult = num1 * num2;
break;
case "/":
reasult = num1 / num2;
break;
}
//输出结果
this.textBox3.Text = string.Format("{0}{1}{2}={3}",num1,this.comboBox1.Text,num2,reasult);
}
private void button2_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
this.textBox2.Text = "";
this.textBox3.Text = "";
}
//清空
}
}
你自己看看代码几效果图吧
从楼上界面图看,应该正解。