本帖最后由 mdb 于 2014-4-8 01:51 编辑
最后手痒还是写了下,思路很简单,先算乘除法,最后算加减,算到最后就是一连串的加减法了,这样就很好处理了,先把整理个字符串给分成只有加减法的列表,然后把列表里有乘除法的项目先算出来再把结果的值存进去,最后整个列表就都是数字和运算符了,这样直接循环进行判断运算就可以了,简单写了个类,不考虑大小括号的运算符,明天再加个功能让它支持括号的表达式。
类
- public class yunshuanshi
- {
- private List<string> all { get; set; }
- public yunshuanshi(string s)
- {
- string[] numarr = s.Split(new char[] { '+', '-' });
- List<string> la = Regex.Split(s.Replace("*", "").Replace("/", ""), @"\d+").Where(r => !string.IsNullOrEmpty(r)).ToList();
- List<string> ls = new List<string>();
- for (int i = 0; i < numarr.Length; i++)
- {
- ls.Add(numarr[i]);
- if (i < la.Count)
- ls.Add(la[i]);
- }
- all = ls;
- }
- public string yunshuan()
- {
- for (int i = 0; i < all.Count; i++) // 先乘除
- {
- if (all[i].Contains("*") || all[i].Contains("/"))
- all[i] = chengchu(all[i]).ToString();
- }
- yunshuanall();// 后加减
- return all[0]; // 结果
- }
- private void yunshuanall()
- {
- double sum = 0;
- while (all.Count != 1)
- {
- switch (all[1])
- {
- case "+":
- sum = double.Parse(all[0]) + double.Parse(all[2]);
- break;
- case "-":
- sum = double.Parse(all[0]) - double.Parse(all[2]);
- break;
- }
- all.RemoveRange(0, 3);
- all.Insert(0, sum.ToString());
- }
- }
- private double chengchu(string s)
- {
- List<string> cx = s.Split(new char[] { '*', '/' }).ToList();
- List<string> fh = Regex.Split(s, @"\d+").Where(r => !string.IsNullOrEmpty(r)).ToList();
- List<string> la = new List<string>();
- for (int i = 0; i < cx.Count; i++)
- {
- la.Add(cx[i]);
- if (i < fh.Count)
- la.Add(fh[i]);
- }
- cx = la;
- double sum = 0;
- while (cx.Count != 1)
- {
- switch (cx[1])
- {
- case "*":
- sum = double.Parse(cx[0]) * double.Parse(cx[2]);
- break;
- case "/":
- sum = double.Parse(cx[0]) / double.Parse(cx[2].Trim() == "0" ? "1" : cx[2].Trim());
- break;
- }
- cx.RemoveRange(0, 3);
- cx.Insert(0, sum.ToString());
- }
- return sum;
- }
- }
复制代码
调用
- yunshuanshi y = new yunshuanshi("2*40*5/2+10-5+4*16/8-5*18/3/2");
- Console.WriteLine("结果是:" + y.yunshuan());
复制代码
简单试算了几个结果都对,不知道还有没有什么BUG |