c#计算器窗体
时间: 2023-07-10 22:10:08 浏览: 134
c#窗体计算器
这是一个基本的 C# 计算器窗体的示例代码:
```csharp
using System;
using System.Windows.Forms;
namespace Calculator
{
public partial class CalculatorForm : Form
{
public CalculatorForm()
{
InitializeComponent();
}
private void NumberButton_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (ResultTextBox.Text == "0")
ResultTextBox.Text = button.Text;
else
ResultTextBox.Text += button.Text;
}
private void OperatorButton_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
string operatorValue = button.Text;
if (!string.IsNullOrEmpty(OperatorLabel.Text))
{
double operand1 = double.Parse(ResultTextBox.Text);
double operand2 = double.Parse(OperandLabel.Text);
double result = Calculate(operand2, operand1, OperatorLabel.Text);
ResultTextBox.Text = result.ToString();
}
OperatorLabel.Text = operatorValue;
OperandLabel.Text = ResultTextBox.Text;
ResultTextBox.Text = "0";
}
private void EqualsButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(OperatorLabel.Text))
{
double operand1 = double.Parse(ResultTextBox.Text);
double operand2 = double.Parse(OperandLabel.Text);
double result = Calculate(operand2, operand1, OperatorLabel.Text);
ResultTextBox.Text = result.ToString();
OperatorLabel.Text = "";
OperandLabel.Text = "";
}
}
private void ClearButton_Click(object sender, EventArgs e)
{
ResultTextBox.Text = "0";
OperatorLabel.Text = "";
OperandLabel.Text = "";
}
private double Calculate(double operand1, double operand2, string operatorValue)
{
switch (operatorValue)
{
case "+":
return operand1 + operand2;
case "-":
return operand1 - operand2;
case "*":
return operand1 * operand2;
case "/":
return operand1 / operand2;
default:
throw new ArgumentException("Invalid operator", "operatorValue");
}
}
}
}
```
这里是一个简单的窗体,有一些按钮用于输入数字和操作符,一个文本框用于显示结果。用户可以按数字按钮输入数字,按运算符按钮执行计算并显示结果。这个窗体支持加、减、乘、除四种基本运算。
阅读全文