用visual studio编写计算器程序的代码
时间: 2024-06-08 15:07:49 浏览: 69
计算器源代码 visual
以下是使用 Visual Studio 编写计算器程序的 C# 代码示例:
```csharp
using System;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
double num1 = 0, num2 = 0, result = 0;
char op = ' ';
public Form1()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (textBox.Text == "0" && btn.Text != ".")
{
textBox.Clear();
}
if (btn.Text == ".")
{
if (!textBox.Text.Contains("."))
{
textBox.Text += btn.Text;
}
}
else
{
textBox.Text += btn.Text;
}
}
private void op_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
op = btn.Text[0];
num1 = double.Parse(textBox.Text);
textBox.Clear();
}
private void equals_Click(object sender, EventArgs e)
{
num2 = double.Parse(textBox.Text);
switch (op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
textBox.Text = result.ToString();
num1 = result;
}
private void clear_Click(object sender, EventArgs e)
{
textBox.Text = "0";
num1 = 0;
num2 = 0;
op = ' ';
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.NumPad0:
case Keys.D0:
button0.PerformClick();
break;
case Keys.NumPad1:
case Keys.D1:
button1.PerformClick();
break;
case Keys.NumPad2:
case Keys.D2:
button2.PerformClick();
break;
case Keys.NumPad3:
case Keys.D3:
button3.PerformClick();
break;
case Keys.NumPad4:
case Keys.D4:
button4.PerformClick();
break;
case Keys.NumPad5:
case Keys.D5:
button5.PerformClick();
break;
case Keys.NumPad6:
case Keys.D6:
button6.PerformClick();
break;
case Keys.NumPad7:
case Keys.D7:
button7.PerformClick();
break;
case Keys.NumPad8:
case Keys.D8:
button8.PerformClick();
break;
case Keys.NumPad9:
case Keys.D9:
button9.PerformClick();
break;
case Keys.Add:
buttonAdd.PerformClick();
break;
case Keys.Subtract:
buttonSubtract.PerformClick();
break;
case Keys.Multiply:
buttonMultiply.PerformClick();
break;
case Keys.Divide:
buttonDivide.PerformClick();
break;
case Keys.Decimal:
buttonDecimal.PerformClick();
break;
case Keys.Enter:
buttonEquals.PerformClick();
break;
case Keys.Delete:
buttonClear.PerformClick();
break;
default:
break;
}
}
}
}
```
在 Visual Studio 中,可以使用 Windows 窗体应用程序模板创建一个新项目,然后将上述代码复制到 Form1.cs 文件中。
阅读全文