C# 简易版的计算器程序

今天无聊,用了半个小时帮一个学生写了一个简单的计算器程序。只有最基本的功能,可以供初学者参考。

下面贴上代码:

 public partial class Form1 : Form
{

private string FuHao; //定义操作符号(+,-,*,/)
private string num1; //定义第一个参数(就是参与运算的第一个数)
private string num2; //定义第二个参数
private string oldValue = "0"; //定义老参数


public Form1()
{
InitializeComponent();
}

//清0操作
private void btn_Clean_Click(object sender, EventArgs e)
{
txt_Vlaue.Text = "0";
FuHao = string.Empty;
oldValue = "0";
}

//获取结果(=号点击事件)
private void btn_GetVlaue_Click(object sender, EventArgs e)
{
if (FuHao == string.Empty)
{
txt_Vlaue.Text = num1.ToString();
}
else
{
GetValue();
}

}

//加法操作
private void btn_add_Click(object sender, EventArgs e)
{
if (num2 != null && num2 != string.Empty)
{
GetValue();
}
FuHao = "+";
oldValue = "0";
}

//减法操作
private void btn_Jian_Click(object sender, EventArgs e)
{
if (num2 != null && num2 != string.Empty)
{
GetValue();
}
FuHao = "-";
oldValue = "0";
}

//乘法操作
private void btn_Cheng_Click(object sender, EventArgs e)
{
if (num2 != null && num2 != string.Empty)
{
GetValue();
}
FuHao = "*";
oldValue = "0";
}

//除法操作
private void btn_Chu_Click(object sender, EventArgs e)
{
if (num2 != null && num2 != string.Empty)
{
GetValue();
}
FuHao = "/";
oldValue = "0";
}

//点击0
private void btn_0_Click(object sender, EventArgs e)
{
InputNum("0");
}

//点击1
private void btn_1_Click(object sender, EventArgs e)
{
InputNum("1");
}

//点击2
private void btn_2_Click(object sender, EventArgs e)
{
InputNum("2");
}

//点击3
private void btn_3_Click(object sender, EventArgs e)
{
InputNum("3");
}

//点击4
private void btn_4_Click(object sender, EventArgs e)
{
InputNum("4");
}

//点击5
private void btn_5_Click(object sender, EventArgs e)
{
InputNum("5");
}

//点击6
private void btn_6_Click(object sender, EventArgs e)
{
InputNum("6");
}

//点击7
private void bvtn_7_Click(object sender, EventArgs e)
{
InputNum("7");
}

//点击8
private void btn_8_Click(object sender, EventArgs e)
{
InputNum("8");
}

//点击9
private void btn_9_Click(object sender, EventArgs e)
{
InputNum("9");
}

//小数点点击
private void btn_point_Click(object sender, EventArgs e)
{
InputNum(".");
}


//数字点击事件
public void InputNum(string value)
{
//如果已经输入数字,则直接累加
if (oldValue != "0")
{
txt_Vlaue.Text = oldValue + value;
}
else
{
//如果第一次输入的是小数点
if (value == ".")
{
txt_Vlaue.Text = "0"+value;
}
else
{
txt_Vlaue.Text = value;
}
}
oldValue = txt_Vlaue.Text;
//如果已经点击了=,-,*,/,那么这个参数是第二个参数
if (FuHao != null && FuHao.ToString().Trim() != string.Empty )
{
num2 = txt_Vlaue.Text;
}
else
{
num1 = txt_Vlaue.Text;
}
}

//获取值
private void GetValue()
{
double numa = double.Parse(num1);
double numb = double.Parse(num2);
double result = 0;
switch (FuHao)
{
case "+":
result = numa + numb;
break;
case "-":
result = numa - numb;
break;
case "*":
result = numa * numb;
break;
default:
result = numa / numb;
break;
}
txt_Vlaue.Text = result.ToString();
FuHao = string.Empty;
oldValue = "0";
num2 = string.Empty;
num1 = txt_Vlaue.Text;
}

 

希望对初学者有帮助。

posted @ 2012-02-20 12:39  唐岗  阅读(...)  评论(...编辑  收藏