//初始化 private void ExpInit(ref string exp) { Operator op = new Operator(); //全/半角&中/英文 exp = exp.Replace('(', '('); exp = exp.Replace(')', ')'); exp = exp.Replace('。', '.'); exp = exp.Replace(',', '.'); exp = exp.Replace(',', '.'); exp = exp.Replace('[', '('); exp = exp.Replace(']', ')'); exp = exp.Replace('{', '('); exp = exp.Replace('}', ')'); exp = exp.Replace('【', '('); exp = exp.Replace('】', ')'); exp = exp.Replace('『', '('); exp = exp.Replace('』', ')'); exp = exp.Replace('_', '-'); exp = exp.Replace('\\', '/'); exp = exp.Replace('П', 'π'); //在括号/数字/函数/常数间插入乘号 bool afterBracket = false; bool afterNum = false; bool afterNumSpace = false; bool afterConst = false; for (int i = 0; i <= exp.Length - 1; i++) { if (op.FindFunc(exp, i) && (afterBracket || afterNum || afterNumSpace || afterConst)) //当前是函数,之前有括号/数字/常数 { exp = exp.Insert(i, "*"); i += 1; } if (op.FindConst(exp, i) && (afterBracket || afterNum || afterNumSpace || afterConst)) //当前是常数,之前有括号/数字/常数 { exp = exp.Insert(i, "*"); i += 1; } if ((exp[i] == '(') && (afterBracket || afterNum || afterNumSpace || afterConst)) //当前是括号,之前有括号/数字/常数 exp = exp.Insert(i, "*"); if (IsDigit(exp[i]) && (afterBracket || afterNumSpace || afterConst)) //当前是数字,之前有括号/数字+空白/常数 exp = exp.Insert(i, "*"); if (IsDigit(exp[i])) //在数字后 { afterBracket = false; afterNum = true; afterNumSpace = false; afterConst = false; continue; } if (exp[i] == ')') //在右括号后 { afterBracket = true; afterNum = false; afterNumSpace = false; afterConst = false; continue; } if (op.FindConst(exp, i)) //在常数后 { afterBracket = false; afterNum = false; afterNumSpace = false; afterConst = true; i += op.opStr.Length - 1; continue; } afterNumSpace = afterNum || afterNumSpace;//在数字与空白符后 if (op.FindWhole(exp, i) || (exp[i] == '(')) { afterBracket = false; afterNum = false; afterNumSpace = false; afterConst = false; if (op.FindWhole(exp, i)) i += op.opStr.Length - 1; continue; } } //替换常数 for (int i = 0; i <= exp.Length - 1; i++) { if (op.FindConst(exp, i)) { exp = exp.Remove(i, op.opStr.Length); switch (op.opStr) { case "en": exp = exp.Insert(i, Convert.ToString(Math.E)); break; case "pi": case "π": exp = exp.Insert(i, Convert.ToString(Math.PI)); break; case "m1": exp = exp.Insert(i, M[1]); break; case "m2": exp = exp.Insert(i, M[2]); break; case "m3": exp = exp.Insert(i, M[3]); break; case "m4": exp = exp.Insert(i, M[4]); break; } } } //预处理正负号 char[] tempExp = exp.ToCharArray(); bool afterOp = true; bool foundOp; for (int i = 0; i <= exp.Length - 1; i++) { if ((exp[i] == '+') && afterOp) tempExp[i] = '~'; if ((exp[i] == '-') && afterOp) tempExp[i] = '_'; foundOp = false; if (op.FindWhole(exp, i) || (exp[i] == '(')) { afterOp = true; foundOp = true; if (op.FindWhole(exp, i)) i += op.opStr.Length - 1; } if (!foundOp) afterOp = false; } exp = new string(tempExp); }