怎么使用C#实现简单的计算器功能(云服务器、云主机、高防IP、高防服务器、香港服务器、美国服务器,开发技术)

时间:2024-05-04 12:51:44 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

环境:VS2010及以上版本

1、建立个Window窗体应用

怎么使用C#实现简单的计算器功能

2、在工具箱里拖出两个TextBox,第一个放上面,第二个放下面 。主要这里的Name,上面是textBox1,下面是textBox2。这涉及到后面代码的书写

怎么使用C#实现简单的计算器功能

3、在工具栏里拖动Button,摆放好。可利用上面的对齐工具辅助设计。

怎么使用C#实现简单的计算器功能

4、在属性里改变各Button的Text,如下

怎么使用C#实现简单的计算器功能

注意这里的1~9,小数点,±*/ 的Text应只有一个字符,不要多输。←

5、选中任意一个Button,右键,选择查看代码,转到Form1.cs

怎么使用C#实现简单的计算器功能

6、开始写代码

AddNum 修改TextBox的Text,应用于1~9与小数点的Click事件
Reset 重置temp、myoperator,以及两个TextBox的Text
Delete 删除textBox2的Text最后一个字符
Calculate 把textBox2的Text转为double给temp,修改myoperator
Equal 具体的计算

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceWindowsFormsApp1{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}//----上面是自动生成的代码,下面得我们手写----privatedoubletemp=0;//存储临时数据privatecharmyoperator='';//判断之前按的是+-*/中的哪个privatevoidAddNum(objectsender,EventArgse){//1~9与小数点的Click事件//sender是引发该事件的控件,这里我们拆箱为ButtonButtonbutton=(Button)sender;textBox2.Text+=button.Text;}privatevoidReset(objectsender,EventArgse){//CE的Click事件temp=0;myoperator='';textBox1.Text=textBox2.Text="";}privatevoidDelete(objectsender,EventArgse){//←的Click事件//移除最后一个字符if(textBox2.TextLength>0)textBox2.Text=textBox2.Text.Remove(textBox2.TextLength-1);}privatevoidCalculate(objectsender,EventArgse){//+-*/的Click事件Buttonbutton=(Button)sender;if(double.TryParse(textBox2.Text,outtemp))//尝试把textBox2的Text转为double并赋值给temp{myoperator=button.Text[0];//Text是string,取第一个字符textBox1.Text=temp.ToString()+''+myoperator;textBox2.Text="";}else{//转换失败,重置所有Reset(sender,e);}}privatevoidEqual(objectsender,EventArgse){//=的Click事件,计算并显示doubletemp2;//尝试转换,失败则重置并返回if(!double.TryParse(textBox2.Text,outtemp2)){Reset(sender,e);return;}switch(myoperator){case'+':temp+=temp2;break;case'-':temp-=temp2;break;case'*':temp*=temp2;break;case'/':temp/=temp2;break;default:break;}textBox1.Text="";textBox2.Text=temp.ToString();}}}

7、设置各Button的Click事件

AddNum: 1~9与小数点的Click事件
Reset:CE的Click事件
Delete:←的Click事件
Calculate :±*/的Click事件
Equal:= 的Click事件

怎么使用C#实现简单的计算器功能

8、启动(F5)

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:怎么使用C#实现简单的计算器功能的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:pytorch如何实现多项式回归下一篇:

11 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18