/// <summary> /// 计算 /// </summary> /// <param name="str">计算符</param> private void Cal(string str) { //符号表为空,而且当前符号为"",则认为已经计算完毕 if (str.Equals("") && HList.Count == 0) { return; } if (HList.Count > 0) { //符号是否可以对消? if (HList[HList.Count - 1].ToString().Equals("(") && str.Equals(")")) { HList.RemoveAt(HList.Count - 1); if (HList.Count > 0) { str = HList[HList.Count - 1].ToString(); HList.RemoveAt(HList.Count - 1); Cal(str); } return; } //比较优先级 if (cu.Compare(HList[HList.Count - 1].ToString(), str)) { //如果优先,则计算 IOper p = of.CreateOper(HList[HList.Count - 1].ToString()); if (p != null) { Vlist[Vlist.Count - 2] = p.Oper(Vlist[Vlist.Count - 2], Vlist[Vlist.Count - 1]); HList.RemoveAt(HList.Count - 1); Vlist.RemoveAt(Vlist.Count - 1); Cal(str); } return; } if (!str.Equals("")) { HList.Add(str); } } else { if (!str.Equals("")) { HList.Add(str); } } }
/// <summary> /// 开始计算 /// </summary> public object DoCal(string str) { /// 算术符栈 ArrayList HList = new ArrayList(); /// 数值栈 ArrayList Vlist = new ArrayList(); //读算试工具 CalUtility cu = new CalUtility(str); FormaItem formaItem = cu.getItem(); while (true) { if (formaItem.Typ == FormaItemType.Number) { //如果是数值,则写入数据栈 Vlist.Add(formaItem.Name); } else if (formaItem.Typ == FormaItemType.Tag) { Vlist.Add(GetTagValue(formaItem.Name).ToString()); } else { string opStr = formaItem.Name; while (HList.Count > 0) { //比较优先级 if (of.MoreThen(HList[HList.Count - 1].ToString(), opStr)) { if (HList[HList.Count - 1].ToString().Equals("(")) { if (opStr.Equals(")")) //符号是否可以对消? { HList.RemoveAt(HList.Count - 1); if (HList.Count > 0) { opStr = HList[HList.Count - 1].ToString(); HList.RemoveAt(HList.Count - 1); } } else { break; } } else { //如果新来操作符优先级低,则计算前面的运算符 IOper p = of.CreateOper(HList[HList.Count - 1].ToString()); if (p != null) { Vlist[Vlist.Count - 2] = p.Oper(Vlist[Vlist.Count - 2], Vlist[Vlist.Count - 1]); HList.RemoveAt(HList.Count - 1); Vlist.RemoveAt(Vlist.Count - 1); } else { break; } } } else { break; } } if (!opStr.Equals("")) { HList.Add(opStr); } else { break; } } formaItem = cu.getItem(); } return(Vlist[0]); }