C# 窗体应用程序计算器代码详解与教程
C# 窗体应用程序计算器代码详解与教程
想要学习如何使用C#创建一个简单的计算器吗?这篇博客将为你提供一个完整的C#窗体应用程序计算器代码示例,并进行详细的代码分析,帮助你轻松入门。
C# 计算器代码
以下是我们创建的C#计算器代码:
using System;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
double num1 = 0;
double num2 = 0;
string operation = '';
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
textBox.Text += button.Text;
}
private void operator_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
operation = button.Text;
num1 = double.Parse(textBox.Text);
textBox.Text = '';
}
private void equal_Click(object sender, EventArgs e)
{
num2 = double.Parse(textBox.Text);
switch (operation)
{
case '+':
textBox.Text = (num1 + num2).ToString();
break;
case '-':
textBox.Text = (num1 - num2).ToString();
break;
case '*':
textBox.Text = (num1 * num2).ToString();
break;
case '/':
textBox.Text = (num1 / num2).ToString();
break;
default:
break;
}
}
private void clear_Click(object sender, EventArgs e)
{
textBox.Text = '';
}
}
}
代码分析
- 窗体设计: 这个计算器程序使用了 Windows Forms 进行界面设计,包含了数字按钮 (0-9), 运算符按钮 (+, -, *, /), 等号按钮 (=) 和 清除按钮 (C)。
- 数字按钮: 当用户点击数字按钮时,对应的数字会添加到文本框中。
- 运算符按钮: 点击运算符按钮时,程序会保存第一个数字 (
num1) 和运算符 (operation),然后清空文本框,准备接收第二个数字。 - 等号按钮: 点击等号按钮时,程序会获取第二个数字 (
num2),然后根据operation执行相应的计算,并将结果显示在文本框中。 - 清除按钮: 点击清除按钮会清空文本框,并将
num1,num2和operation重置为初始值。
总结
这个简单的C#窗体应用程序计算器代码示例展示了如何使用 Windows Forms 创建用户界面,并通过按钮事件处理用户输入和计算结果。你可以根据自己的需求,扩展这个程序的功能,例如添加更多运算符、实现更复杂的计算逻辑等。
原文地址: https://www.cveoy.top/t/topic/fMue 著作权归作者所有。请勿转载和采集!