打开VisualStudio2005患束锍瓜开发工具,新建一个Windows应用程序,然后在窗体上依次放置1个TextBox和14个Button控件,如图4-1所示(设置好属性后)。
方法/步骤
1、设置图片中控件的相关属性
2、编写代码本程序需要用到一些公共变量,例如用来接收操作数、运算结果,判断输入的是豸阏恢闲否为小数等,因此首先在代码的通用段声明以下变量:doublenum1,num2,resul墉掠载牿t;//操作数及运算结果booldecimalFlag;//判断输入的是否为小数stringmyOperator;//操作类型接下来编写一个名为“NumClick”的方法,单击数字按钮时,调用NumClick方法,将输入的数字追加到文本框中,代码如下:publicvoidNumClick(intmyNumber){if(decimalFlag)//输入小数{txtReadout.Text=txtReadout.Text+myNumber;}else{if(txtReadout.Text=="0.")//输入整数{//输入的是整数的个位数字txtReadout.Text=myNumber+".";}else{//输入的不是整数的个位数字txtReadout.Text=txtReadout.Text.Substring0,txtReadout.Text.Length-1)+myNumber+".";}}}编写窗体的载入事件代码如下:privatevoidForm1_Load(objectsender,EventArgse){txtReadout.Text="0.";//指定文本框的对齐方式为右对齐txtReadout.TextAlign=HorizontalAlignment.Right;}编写数字按钮【0】~【9】的单击事件代码如下:privatevoidbtnNum0_Click(objectsender,EventArgse){NumClick(0);}privatevoidbtnNum1_Click(objectsender,EventArgse){NumClick(1);}privatevoidbtnNum2_Click(objectsender,EventArgse){NumClick(2);}privatevoidbtnNum3_Click(objectsender,EventArgse){NumClick(3);}privatevoidbtnNum4_Click(objectsender,EventArgse){NumClick(4);}privatevoidbtnNum5_Click(objectsender,EventArgse){NumClick(5);}privatevoidbtnNum6_Click(objectsender,EventArgse){NumClick(6);}privatevoidbtnNum7_Click(objectsender,EventArgse){NumClick(7);}privatevoidbtnNum8_Click(objectsender,EventArgse){NumClick(8);}privatevoidbtnNum9_Click(objectsender,EventArgse){NumClick(9);}编写小数点按钮【.】的单击事件代码如下:privatevoidbtnDot_Click(objectsender,EventArgse){decimalFlag=true;//输入小数点}编写复位按钮【C】的单击事件代码如下:privatevoidbtnC_Click(objectsender,EventArgse){num1=0;num2=0;txtReadout.Text="0.";}编写【+】、【-】、【*】、【/】按钮的单击事件代码如下:privatevoidbtnAdd_Click(objectsender,EventArgse){myOperator="add";num1=double.Parse(txtReadout.Text);txtReadout.Text="0.";decimalFlag=false;}privatevoidbtnSub_Click(objectsender,EventArgse){myOperator="Sub";num1=double.Parse(txtReadout.Text);txtReadout.Text="0.";decimalFlag=false;}privatevoidbtnMul_Click(objectsender,EventArgse){myOperator="Mul";num1=double.Parse(txtReadout.Text);txtReadout.Text="0.";decimalFlag=false;}privatevoidbtnDiv_Click(objectsender,EventArgse){myOperator="Div";num1=double.Parse(txtReadout.Text);txtReadout.Text="0.";decimalFlag=false;}最后编写【=】按钮的单击事件代码如下:privatevoidbtnAmount_Click(objectsender,EventArgse){num2=double.Parse(txtReadout.Text);switch(myOperator){case"add":result=num1+num2;txtReadout.Text=result.ToString();break;case"Sub":result=num1-num2;txtReadout.Text=result.ToString();break;case"Mul":result=num1*num2;txtReadout.Text=result.ToString();break;case"Div":if(num2==0){txtReadout.Text="除数不能为“0”!";}else{result=num1/num2;txtReadout.Text=result.ToString();}break;}}
3、运行结果运行程序,计算加法“23+1.8”
4、单击【C】按钮,再计算加法“2.3-18”
5、单击【C】按钮,再计算加法“2.3×1.8”
6、单击【C】按钮,再计算加法“23.18÷0”
7、单击【C】按钮,再计算加法“2.3÷1.8”