C# 窗体程序实现简单计算器
以下是用 C# 编写的一个简单的计算器,可以实现加、减、乘、除运算:
using System;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
private double num1 = 0; // 第一个操作数
private double num2 = 0; // 第二个操作数
private string operation = ''; // 运算符
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
string buttonText = button.Text;
// 检查按钮上的文本是数字还是运算符
if (buttonText == '+' || buttonText == '-' || buttonText == '*' || buttonText == '/')
{
// 如果已经有第一个操作数和运算符,则进行运算
if (num1 != 0 && operation != '')
{
num2 = double.Parse(textBox.Text);
num1 = Calculate(num1, num2, operation);
textBox.Text = num1.ToString();
}
// 保存第一个操作数和运算符
num1 = double.Parse(textBox.Text);
operation = buttonText;
textBox.Text = '';
}
else if (buttonText == '=')
{
// 如果有第一个操作数和运算符,则进行运算
if (num1 != 0 && operation != '')
{
num2 = double.Parse(textBox.Text);
num1 = Calculate(num1, num2, operation);
textBox.Text = num1.ToString();
num1 = 0; // 重置第一个操作数
operation = ''; // 重置运算符
}
}
else if (buttonText == 'C')
{
// 清除文本框内容并重置所有变量
textBox.Text = '';
num1 = 0;
num2 = 0;
operation = '';
}
else
{
// 将按钮上的数字添加到文本框中
textBox.Text += buttonText;
}
}
private double Calculate(double num1, double num2, string operation)
{
double result = 0;
switch (operation)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
return result;
}
}
}
这是一个窗体应用程序,其中包含一个文本框和一组按钮。通过单击按钮来输入数字和运算符,并将结果显示在文本框中。运算符按钮上的button_Click事件处理程序负责执行相应的操作。
原文地址: http://www.cveoy.top/t/topic/pMxZ 著作权归作者所有。请勿转载和采集!