基本信息
源码名称:C# 计算器(入门级示例源码下载)
源码大小:0.07M
文件格式:.zip
开发语言:C#
更新时间:2016-07-22
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍

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;
using System.Text.RegularExpressions;

namespace Calculator
{
    public partial class MainForm : Form
    {
        bool isOver = false; //标记一次运算是否结束,true为结束,false为没结束
        bool isMinus = false; //判断一个数是否为负数,true为负,false为正
        string s1 = null;
        Stack<string> optr = new Stack<string>();  //运算符栈
        Stack<double> opnd = new Stack<double>();  //运算数栈
        public MainForm()
        {
            InitializeComponent();
            txtFormula.Focus();
            optr.Push("=");
        }

        /*private void txtFormula_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8 && e.KeyChar != (char)(' ') && e.KeyChar != (char)('-')
                && e.KeyChar != (char)('*') && e.KeyChar != (char)('/') && e.KeyChar != (char)('(') && e.KeyChar != (char)(')')
                && e.KeyChar != (char)('.') && e.KeyChar != (char)('^'))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }*/


        /// <summary>
        /// 操作数处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnNum_Click(object sender, EventArgs e)
        {
            if (isOver == true) //清屏
            {
                txtFormula.Clear();
                txtResult.Clear();
                isOver = false;
                isMinus = false;
            }
            Button btnNum = sender as Button;
            s1  = btnNum.Text; //存储操作数
            txtFormula.SelectedText = btnNum.Text;
            txtFormula.Focus();
            txtFormula.SelectionStart = txtFormula.TextLength;
        }

        private void btnPm_Click(object sender, EventArgs e)
        {
            double n = 0;
            try
            {
                if (s1 != null)   //操作数入栈
                {
                    n = Double.Parse(s1);
                    if (isMinus == true)
                    {
                        n = -n;
                        isMinus = false;
                    }
                    opnd.Push(n);
                    s1 = null;
                }
                txtFormula.SelectedText = "-";
            }
            catch
            {
                MessageBox.Show("Error!");
                txtFormula.Clear();
                txtResult.Clear();
                optr.Clear();
                opnd.Clear();
                optr.Push("=");
                s1 = null;
            }
            isMinus = true;
        }

        /// <summary>
        /// 运算处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Calculate(object sender, EventArgs e)
        {
            if (isOver == true)//清屏
            {
                txtFormula.Clear();
                txtResult.Clear();
                isOver = false;
                isMinus = false;
            }
            double n = 0;
            try
            {
                //MessageBox.Show(s1);
                if (s1 != null)   //操作数入栈
                {
                    n = Double.Parse(s1);
                    if (isMinus == true)
                    {
                        n = -n;
                        isMinus = false;
                    }
                    opnd.Push(n);
                    s1 = null;
                }
            }
            catch
            {
                MessageBox.Show("Error!");
                txtFormula.Clear();
                txtResult.Clear();
                optr.Clear();
                opnd.Clear();
                optr.Push("=");
                s1 = null;
            }
            Button btnOp = sender as Button;
            string op1 = btnOp.AccessibleName;
            bool flag = true;
            try
            {
                while (flag)
                {
                    string op2 = optr.Peek();
                    switch (Precede(op2, op1)) //查找优先级,并根据结果进行不同操作
                    {
                        case '<': //当前运算符优先权较大,直接入栈,置于栈顶(优先级高需先计算)
                            optr.Push(op1);
                            flag = false;
                            break;
                        //等于则表示栈顶元素为左括号,当前字符为右括号
                        case '=':
                            flag = false;
                            break;
                        //当前运算符优先级小,则弹出栈顶运算符并从操作数栈弹出两个操作数
                        case '>':
                            if (op1.CompareTo(")") == 0)
                            {
                                while (optr.Peek().CompareTo("(") != 0)
                                {
                                    string s2 = optr.Pop();
                                    //注意计算的顺序,计算结果入操作数栈,并且继续比较新的栈顶操作符和当前操作符的优先级

                                    if (s2.Length > 1)
                                    {
                                        double num = opnd.Pop();
                                        opnd.Push(Calculate_2(num, s2));
                                    }
                                    else
                                    {
                                        double num1 = opnd.Pop();
                                        double num2 = opnd.Pop();
                                        opnd.Push(Calculate_1(num1, s2, num2));
                                    }
                                }
                                optr.Pop();
                                flag = false;
                            }
                            else
                            {
                                op2 = optr.Pop();
                                if (op2.Length > 1)
                                {
                                    double num = opnd.Pop();
                                    opnd.Push(Calculate_2(num, op2));
                                }
                                else
                                {
                                    double num1 = opnd.Pop();
                                    double num2 = opnd.Pop();
                                    opnd.Push(Calculate_1(num1, op2, num2));
                                }
                            }
                            break;
                    }
                }
                if (op1.CompareTo("=") == 0)
                {
                    //optr.Pop();
                    if (isMinus || opnd.Count() > 1)
                    {
                        throw new Exception();
                    }
                    while (optr.Peek().CompareTo("=") != 0)
                    {
                        double n1 = opnd.Pop();
                        double n2 = opnd.Pop();
                        string op = optr.Pop();
                        opnd.Push(Calculate_1(n1, op, n2));
                    }
                    txtResult.Text = ""   opnd.Pop();
                    optr.Clear();
                    opnd.Clear();
                    optr.Push("=");
                    isOver = true;
                }
                else
                {
                    txtFormula.SelectedText = btnOp.AccessibleName;
                }
            }
            catch
            {
                //MessageBox.Show(ee.Message);
                MessageBox.Show("Error!");
                txtFormula.Clear();
                txtResult.Clear();
                optr.Clear();
                opnd.Clear();
                optr.Push("=");
                s1 = null;
            }
            txtFormula.Focus();
            txtFormula.SelectionStart = txtFormula.TextLength;
        }

        /// <summary>
        /// 优先级列表
        /// </summary>
        /// <param name="first"></param>
        /// <param name="last"></param>
        /// <returns></returns>
        private char Precede(string first, string last)
        {
            string[] operate = { " ", "-", "*", "/", "(", ")", "#", "=" };
            char[,] level = new char[8, 8]{
                                         { '>', '>', '<', '<', '<', '>', '<', '>' },//定义各种运算符优先级数组
                                         { '>', '>', '<', '<', '<', '>', '<', '>' },
                                         { '>', '>', '>', '>', '<', '>', '<', '>' },
                                         { '>', '>', '>', '>', '<', '>', '<', '>' },
                                         { '<', '<', '<', '<', '<', '>', '<', '>' },
                                         { '>', '>', '>', '>', '>', '>', '<', '>' },
                                         { '>', '>', '>', '>', '<', '>', '<', '>' },
                                         { '<', '<', '<', '<', '<', '<', '<', '=' }
            };
            int rows = Array.IndexOf(operate, first);
            int cols = Array.IndexOf(operate, last);
            if (rows == -1)
            {
                rows = 6;
            }
            if (cols == -1)
            {
                cols = 6;
            }
            return level[rows, cols];
        }

        /// <summary>
        /// 加减乘除平方
        /// </summary>
        /// <param name="num1"></param>
        /// <param name="op"></param>
        /// <param name="num2"></param>
        /// <returns></returns>
        private double Calculate_1(double num1, string op, double num2)
        {
            switch (op)
            {
                case " ":
                    return num1   num2;
                case "-":
                    return num2 - num1;
                case "*":
                    return num1 * num2;
                case "/":
                    return num2 / num1;
                case "^":
                    return Math.Pow(num2, num1);
            }
            return 0;
        }

        /// <summary>
        /// 三角函数,ln函数,开方运算
        /// </summary>
        /// <param name="num"></param>
        /// <param name="op"></param>
        /// <returns></returns>
        private double Calculate_2(double num, string op)
        {
            switch (op)
            {
                case "sin":
                    return Math.Sin(num * Math.PI / 180);
                case "cos":
                    return Math.Cos(num * Math.PI / 180);
                case "tan":
                    return Math.Tan(num * Math.PI / 180);
                case "ln":
                    return Math.Log(num);
                case "√ ̄":
                    return Math.Sqrt(num);
            }
            return 0;
        }

        /// <summary>
        /// 关联键盘输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (e.KeyChar)
            {
                case '0':
                    btn0.PerformClick();// 按键盘"0"键执行按钮“0”的操作
                    e.Handled = true;
                    break;
                case '1':
                    btn1.PerformClick();// 按键盘"1"键执行按钮“1”的操作
                    e.Handled = true;
                    break;
                case '2':
                    btn2.PerformClick();// 按键盘"2"键执行按钮“2”的操作
                    e.Handled = true;
                    break;
                case '3':
                    btn3.PerformClick();// 按键盘"3"键执行按钮“3”的操作
                    e.Handled = true;
                    break;
                case '4':
                    btn4.PerformClick();// 按键盘"4"键执行按钮“4”的操作
                    e.Handled = true;
                    break;
                case '5':
                    btn5.PerformClick();// 按键盘"5"键执行按钮“5”的操作
                    e.Handled = true;
                    break;
                case '6':
                    btn6.PerformClick();// 按键盘"6"键执行按钮“6”的操作
                    e.Handled = true;
                    break;
                case '7':
                    btn7.PerformClick();// 按键盘"7"键执行按钮“7”的操作
                    e.Handled = true;
                    break;
                case '8':
                    btn8.PerformClick();// 按键盘"8"键执行按钮“8”的操作
                    e.Handled = true;
                    break;
                case '9':
                    btn9.PerformClick();// 按键盘"9"键执行按钮“9”的操作
                    e.Handled = true;
                    break;
                case '^':
                    btnSquare.PerformClick();// 按键盘"^"键执行按钮“x^y”的操作
                    e.Handled = true;
                    break;
                case '(':
                    btnLeft.PerformClick();// 按键盘"("键执行按钮“(”的操作
                    e.Handled = true;
                    break;
                case ')':
                    btnRight.PerformClick();// 按键盘")"键执行按钮“)”的操作
                    e.Handled = true;
                    break;
                case ' ':
                    btnAdd.PerformClick();// 按键盘" "键执行按钮“ ”的操作
                    e.Handled = true;
                    break;
                case '-':
                    btnSub.PerformClick();// 按键盘"-"键执行按钮“-”的操作
                    e.Handled = true;
                    break;
                case '*':
                    btnMul.PerformClick();// 按键盘"*"键执行按钮“*”的操作
                    e.Handled = true;
                    break;
                case '/':
                    btnDiv.PerformClick();// 按键盘"/"键执行按钮“/”的操作
                    e.Handled = true;
                    break;
                case (char)8:           // 按键盘"Backspace"键执行删除操作
                    e.Handled = false;
                    if (isOver == true)
                    {
                        txtFormula.Clear();
                        txtResult.Clear();
                        isOver = false;
                        isMinus = false;
                    }                 
                    else if (s1.Length > 1)
                    {
                        s1 = s1.Substring(0, s1.Length - 1);                        
                    }
                    else
                    {
                        s1 = null;
                    }
                    break;
                case (char)13:       //按键盘"Enter"键执行按钮“=”的操作
                    btnCount.PerformClick();
                    e.Handled = true;
                    break;
                default:
                    e.Handled = true;
                    break;
            }
        }
    }
}