這篇文章主要介紹了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#實現簡易的計算器功能詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!