用 c#winfrom做一个科学计算器,用上stack考虑括号
时间: 2024-02-11 09:09:17 浏览: 70
基于C#winfrom开发的科学计算器
好的,加入括号的科学计算器需要更复杂的逻辑和算法,但是使用 Stack 仍然可以很方便地处理括号。
以下是一个示例代码,可以处理带有括号的科学计算器:
```
public partial class Form1 : Form
{
Stack<double> numberStack = new Stack<double>();
Stack<string> operatorStack = new Stack<string>();
public Form1()
{
InitializeComponent();
}
private void btnNumber_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
txtResult.Text += btn.Text;
}
private void btnOperator_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string op = btn.Text;
// 处理括号
if (op == "(")
{
operatorStack.Push(op);
}
else if (op == ")")
{
while (operatorStack.Count > 0 && operatorStack.Peek() != "(")
{
double num2 = numberStack.Pop();
double num1 = numberStack.Pop();
string oper = operatorStack.Pop();
double result = Calculate(num1, num2, oper);
numberStack.Push(result);
}
operatorStack.Pop(); // 弹出左括号
}
else // 处理普通的运算符
{
while (operatorStack.Count > 0 && Priority(operatorStack.Peek()) >= Priority(op))
{
double num2 = numberStack.Pop();
double num1 = numberStack.Pop();
string oper = operatorStack.Pop();
double result = Calculate(num1, num2, oper);
numberStack.Push(result);
}
operatorStack.Push(op);
}
txtResult.Text = "";
}
private void btnEquals_Click(object sender, EventArgs e)
{
double num = double.Parse(txtResult.Text);
numberStack.Push(num);
while (operatorStack.Count > 0)
{
double num2 = numberStack.Pop();
double num1 = numberStack.Pop();
string oper = operatorStack.Pop();
double result = Calculate(num1, num2, oper);
numberStack.Push(result);
}
txtResult.Text = numberStack.Pop().ToString();
}
// 计算两个数的结果
private double Calculate(double num1, double num2, string op)
{
switch (op)
{
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
return num1 / num2;
default:
throw new InvalidOperationException("Invalid operator: " + op);
}
}
// 获取运算符的优先级
private int Priority(string op)
{
switch (op)
{
case "+":
case "-":
return 1;
case "*":
case "/":
return 2;
case "(":
case ")":
return 0;
default:
throw new InvalidOperationException("Invalid operator: " + op);
}
}
}
```
在这个示例代码中,我们使用了两个 Stack:一个存储数字,一个存储运算符。当用户按下数字键时,我们将数字添加到结果框中。当用户按下运算符键时,我们根据运算符的优先级处理运算符,并将运算符推入 Stack 中。当用户按下“=”键时,我们从 Stack 中弹出数字和运算符,并使用它们来计算结果。对于括号,我们需要特殊处理:当遇到左括号时,将其推入运算符 Stack 中;当遇到右括号时,弹出运算符 Stack 中的运算符,并计算相应的结果,直到遇到左括号。
希望这个示例代码可以帮助您实现一个带有括号的科学计算器!
阅读全文