winfrom实现加减乘除
时间: 2023-06-29 16:06:46 浏览: 71
以下是一个简单的 WinForm 程序,可以实现加减乘除四则运算:
```csharp
using System;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
double num1 = Convert.ToDouble(textBox1.Text);
double num2 = Convert.ToDouble(textBox2.Text);
double result = num1 + num2;
label1.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
double num1 = Convert.ToDouble(textBox1.Text);
double num2 = Convert.ToDouble(textBox2.Text);
double result = num1 - num2;
label1.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
double num1 = Convert.ToDouble(textBox1.Text);
double num2 = Convert.ToDouble(textBox2.Text);
double result = num1 * num2;
label1.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
double num1 = Convert.ToDouble(textBox1.Text);
double num2 = Convert.ToDouble(textBox2.Text);
double result = num1 / num2;
label1.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
```
在窗体设计器中添加两个 TextBox 控件和一个 Label 控件,并为每个按钮添加 Click 事件处理程序,分别实现加、减、乘、除四种运算。注意异常处理,避免用户输入非法字符或除数为 0 引发异常。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)