用c#实现简易的计算器功能实例代码

编程入门 行业动态 更新时间:2024-10-15 14:17:51
这篇文章主要介绍了c#实现简易的计算器功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

由于今天在网上搜了一下c#写的计算器,发现大多都太繁琐了,很多没必要并且不容易理解的东西就专门写了这个博客

1.首先新建一个windows窗体应用的项目。执行文件-新建-项目-windows窗体应用

2.在工具箱中拖出一个textbox用于输入和显示,再拖出21个button按钮用来当计算器的按键,在textbox下面还有一个lable控件(我把它属性改成了空格所以看不到了),改一下按钮的text属性

3.双击数字按钮进入代码界面(数字只用一个事件即可,运算符也是用一个事件,其他每个按钮都需要双击添加事件)

4.代码呢已经准备好了,只要双击按钮进入代码界面,然后对应着粘上就行了(注意所有数字都是用的一个事件,都有标注,可以选择按钮,然后单击属性里的事件(闪电图标)查看click的事件)

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace 计算器{public partial class Form3 : Form{public Form3(){InitializeComponent();}//定义变量char oper;double num1;double num2;double result = 0;double memory=0.0;private void Button9_Click(object sender, EventArgs e)//数字按钮的功能实现{Button a = (Button)sender;//判断按下的是哪个按钮if (textBox1.Text == “0”){textBox1.Text = a.Text;}elsetextBox1.Text += a.Text;}private void Button16_Click(object sender, EventArgs e)//运算符按钮的功能实现 { if (textBox1.Text != "") { num1 = double.Parse(textBox1.Text); oper = char.Parse(((Button)sender).Text); textBox1.Text = ""; } } private void Button15_Click(object sender, EventArgs e)//C按钮的功能实现 { textBox1.Text = ""; textBox1.Focus(); num1 = 0; num2 = 0; oper = ' '; } private void Button14_Click(object sender, EventArgs e)//结果按钮的功能实现 { if (textBox1.Text != "") { num2 = double.Parse(textBox1.Text); switch (oper) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '÷': result = num1 / num2; break; } textBox1.Text = result.ToString(); } } private void Button17_Click(object sender, EventArgs e)//小数点按钮的功能实现 { if (textBox1.Text != "") { textBox1.Text += "."; } else { textBox1.Text = "0."; } } private void Button18_Click(object sender, EventArgs e)//M+按钮的功能实现 { if(textBox1.Text!="") { label1.Text = "M"; memory += double.Parse(textBox1.Text); textBox1.Text = " "; } } private void Button20_Click(object sender, EventArgs e)//MR按钮的功能实现 { textBox1.Text = memory.ToString(); } private void Button21_Click(object sender, EventArgs e)//MC按钮的功能实现 { label1.Text = ""; memory = 0; } private void Button19_Click(object sender, EventArgs e)//M-按钮的功能实现 { if (textBox1.Text != "") { label1.Text = "M"; memory -= double.Parse(textBox1.Text); textBox1.Text = " "; } }}

以上所述是小编给大家介绍的c#实现简易的计算器功能详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

用c#实现简易的计算器功能实例代码

本文发布于:2023-06-11 14:51:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/637065.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计算器   简易   实例   代码   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!