实例介绍
【实例简介】
【实例截图】
【核心代码】
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;
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论