这里只会展示成果,记录一下我实现的过程。
用wpf做界面,不用多说,将各个按钮对应数字或者运算符,点击‘=’号的时候将字符串放入写好的算法中得出结果。
当然,算法也是我自己写的,不能显示错误表达式,在一些小范围数据还是可以接受的,只是突发奇想想写这个,但是算法没有经过测试,正确率有待提高。
这里展示一下无括号的 ‘加减乘除’ 计算方法
思路很简单,数字和符号分开储存,然后计算局部结果最后存入栈中,最后取出栈中元素全部相加。
当然如果有括号的,直接使用递归或者栈计算局部结果,最后也是将结果放入栈中求和。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Calculator.Algorithm
{
public class NoParentheses
{
public string? str { get; set; }
private Stack<decimal> st = new Stack<decimal>();
private string[] sArry;
private List<char> list;
public NoParentheses()
{
sArry = new string[] { };
list = new List<char>();
}
public decimal Compute(string str)
{
this.str = str;
list.Clear();
sArry = str.Split(new char[] { '+', '*', '/', '-' }, StringSplitOptions.RemoveEmptyEntries);
/*
* list储存符号,sArry储存数字
* 因为输入的第一个是正数无符号的,所以判断一下是否第一个数要‘+’号
*/
if (str[0] != '-')
{
list.Add('+');
}
foreach (char s in str)
{
if (s == '-' || s == '*' | s == '/' || s == '+')
{
list.Add(s);
}
}
//Console.WriteLine($"{list.Count}+{sArry.Length}");
/*
* 开始运算,将所有运算结果储存到栈里
* 最后直接相加
*/
for (int i = 0; i < list.Count; i++)
{
if (list[i] == '+')
{
st.Push(decimal.Parse(sArry[i]));
}
else if (list[i] == '-')
{
st.Push(-decimal.Parse(sArry[i]));
}
else if (list[i] == '*')
{
decimal p = st.Pop();
p *= decimal.Parse(sArry[i]);
st.Push(p);
}
else
{
decimal p = st.Pop();
p /= decimal.Parse(sArry[i]);
st.Push(p);
}
}
decimal res = 0;
//最后结果相加
while (st.Count != 0)
{
res += st.Pop();
}
return res;
}
}
}