C#计算器窗体程序
我用C#做了一个计算器窗体程序,做好窗体后对应写了如下代码,但实现不了计算,请各位大师帮忙看看,谢谢!using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//(1)定义窗体的公共变量
string str, opp, opp1;
double num1, num2, result;
//(2)编写“数字键”的单击事件代码
private void number(object sender, EventArgs e)
{
Button b = (Button)(sender);
str = b.Text;
if (textBox1.Text == "0")
{
textBox1.Text = str;
}
else
textBox1.Text = textBox1.Text + str;
}
//(3)编写“+ 、-、*、/”操作符键的单击事件代码
private void operational(object sender, EventArgs e)
{
Button b = (Button)(sender);
if (b.Text == "+")
{
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
opp = "+";
opp1 = "";
}
else if (b.Text == "-")
{
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
opp = "-";
opp1 = "";
}
else if (b.Text == "*")
{
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
opp = "*";
opp1 = "";
}
else if (b.Text == "/")
{
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
opp = "/";
opp1 = "";
}
else if (b.Text == "=")
{
if (opp1 != "=")
{
num2 = double.Parse(textBox1.Text);
}
if (opp == "+")
{
num1 = num1 + num2;
textBox1.Text = "" + num1.ToString();
}
else if (opp == "-")
{
num1 = num1 - num2;
textBox1.Text = "" + num1.ToString();
}
else if (opp == "*")
{
num1 = num1 * num2;
textBox1.Text = "" + num1.ToString();
}
else if (opp == "/")
{
if (num2 == 0)
{
textBox1.Text = "除数不能为零";
}
else
{
num1 = num1 / num2;
textBox1.Text = "" + num1.ToString();
}
}
opp1 = "=";
}
}
//(4)编写操作符键“退格<--、CE、C、sqrt、%、1/x、+/-、.”等按钮的单击事件代码
private void operation(object sender, EventArgs e)
{
Button b = (Button)(sender);
if (b.Text == "+/-")
{
num1 = double.Parse(textBox1.Text);
result = num1 * (-1);
textBox1.Text = result.ToString();
}
else if (b.Text == ".")
{
str = textBox1.Text;
int index = str.IndexOf(".");
if (index == -1)
{
textBox1.Text = str + ".";
}
}
else if (b.Text == "退格<--")
{
if (textBox1.Text != "")
{
str = textBox1.Text;
str = str.Substring(0, str.Length - 1);
textBox1.Text = str;
}
}
else if (b.Text == "CE")
{
textBox1.Text = "0";
}
else if (b.Text == "C")
{
result = num1 = num2 = 0;
str = null;
opp = null;
textBox1.Text = "0";
}
else if (b.Text == "sqrt")
{
num1 = double.Parse(textBox1.Text);
result = Math.Sqrt(num1);
textBox1.Text = result.ToString();
}
else if (b.Text == "1/x")
{
num1 = double.Parse(textBox1.Text);
result = 1 / num1;
textBox1.Text = result.ToString();
}
else if (b.Text == "%")
{
num1 = double.Parse(textBox1.Text);
result = num1 / 100;
textBox1.Text = result.ToString();
}
opp1 = "";
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}