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,包含了数字按钮、运算符按钮、等号按钮和清除按钮。当用户点击数字按钮时,数字会显示在文本框中。当用户点击运算符按钮时,程序会保存第一个数字和运算符,并清空文本框。当用户点击等号按钮时,程序会根据保存的数字和运算符进行计算,并将结果显示在文本框中。当用户点击清除按钮时,文本框会被清空。
这个计算器使用了双精度浮点数来保存数字,并使用了 switch 语句来根据运算符执行相应的计算。
原文地址: http://www.cveoy.top/t/topic/h4H8 著作权归作者所有。请勿转载和采集!