用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;
}
else
textBox1.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#实现简易的计算器功能详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对呐喊教程网站的支持!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。