用c#實現(xiàn)簡易的計算器功能實例代碼
由于今天在網(wǎng)上搜了一下c#寫的計算器,發(fā)現(xiàn)大多都太繁瑣了,很多沒必要并且不容易理解的東西就專門寫了這個博客
1.首先新建一個windows窗體應(yīng)用的項目。執(zhí)行文件-新建-項目-windows窗體應(yīng)用
2.在工具箱中拖出一個textbox用于輸入和顯示,再拖出21個button按鈕用來當(dāng)計算器的按鍵,在textbox下面還有一個lable控件(我把它屬性改成了空格所以看不到了),改一下按鈕的text屬性

3.雙擊數(shù)字按鈕進(jìn)入代碼界面(數(shù)字只用一個事件即可,運算符也是用一個事件,其他每個按鈕都需要雙擊添加事件)
4.代碼呢已經(jīng)準(zhǔn)備好了,只要雙擊按鈕進(jìn)入代碼界面,然后對應(yīng)著粘上就行了(注意所有數(shù)字都是用的一個事件,都有標(biāo)注,可以選擇按鈕,然后單擊屬性里的事件(閃電圖標(biāo))查看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)//數(shù)字按鈕的功能實現(xiàn)
{
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)//運算符按鈕的功能實現(xiàn)
{
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按鈕的功能實現(xiàn)
{
textBox1.Text = "";
textBox1.Focus();
num1 = 0;
num2 = 0;
oper = ' ';
}
private void Button14_Click(object sender, EventArgs e)//結(jié)果按鈕的功能實現(xiàn)
{
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)//小數(shù)點按鈕的功能實現(xiàn)
{
if (textBox1.Text != "")
{
textBox1.Text += ".";
}
else
{
textBox1.Text = "0.";
}
}
private void Button18_Click(object sender, EventArgs e)//M+按鈕的功能實現(xiàn)
{
if(textBox1.Text!="")
{
label1.Text = "M";
memory += double.Parse(textBox1.Text);
textBox1.Text = " ";
}
}
private void Button20_Click(object sender, EventArgs e)//MR按鈕的功能實現(xiàn)
{
textBox1.Text = memory.ToString();
}
private void Button21_Click(object sender, EventArgs e)//MC按鈕的功能實現(xiàn)
{
label1.Text = "";
memory = 0;
}
private void Button19_Click(object sender, EventArgs e)//M-按鈕的功能實現(xiàn)
{
if (textBox1.Text != "")
{
label1.Text = "M";
memory -= double.Parse(textBox1.Text);
textBox1.Text = " ";
}
}
}
以上所述是小編給大家介紹的c#實現(xiàn)簡易的計算器功能詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
C#實現(xiàn)json格式數(shù)據(jù)解析功能的方法詳解
這篇文章主要介紹了C#實現(xiàn)json格式數(shù)據(jù)解析功能的方法,結(jié)合實例形式較為詳細(xì)的分析了C#解析json格式數(shù)據(jù)的具體操作步驟與相關(guān)注意事項,需要的朋友可以參考下2017-12-12

