当前位置: 首页 > 编程语言 > C#

如何在C#中解析数学表达式?分享

时间:2023-04-10 20:04:20 C#

C#中如何解析数学表达式?可能重复:.NET中是否有字符串数学计算器?C#能否将像y=3*x+3这样的数学表达式解析为字符串?如果是,好吗?我感谢您的帮助。这是我前段时间写的一些代码来解析中缀(运算符操作数运算符)方程。缺少一些小类和辅助函数,但实现它们应该相当容易。如果您需要它们或任何帮助,请告诉我,我可以将它们上传到某个地方。这是Dijkstra的调车场算法的基础实现publicOperandExpressionTree{get;私有集;私人堆栈堆栈=新堆栈();私有队列outputQueue=newQueue();privatevoidParseFormulaString(){//Dijkstra调车场算法Regexre=newRegex(@"([+-*()^/])");列表tokenList=re.Split(formulaString).Select(t=>t.Trim()).Where(t=>t!="").ToList();对于(inttokenNumber=0;tokenNumber0){StringstackTopToken=stack.Peek().Token;if(GetTokenClass(stackTopToken)==TokenClass.Operator){关联性tokenAssociativity=GetOperatorAssociativity(token);inttokenPrecedence=GetOperatorPrecedence(token);intstackTopPrecedence=GetOperatorPrecedence(stackTopToken);if(tokenAssociativity==Associativity.Left&&tokenPrecedence0&&stack.Peek()isFunction){outputQueue.Enqueue(stack.Pop());}休息;}if(tokenClass==TokenClass.Value||tokenClass==TokenClass.RightParen){if(tokenNumber0){操作数op和=stack.Pop();if(operandisLeftParenthesis||operandisRightParenthesis){thrownewArgumentException("括号不匹配");}outputQueue.Enqueue(操作数);}Stringfoo=String.Join(",",outputQueue.Select(t=>t.Token).ToArray());Stringbar=String.Join("",tokenList.ToArray());堆栈表达式Stack=newStack();while(outputQueue.Count>0){Operandoperand=outputQueue.Dequeue();if(operandisValue){expressionStack.Push(operand);}else{if(operandisBinaryOperator){BinaryOperatorop=(BinaryOperator)operand;操作数rightOperand=expressionStack.Pop();操作数leftOperand=expressionStack.Pop();op.LeftOperand=leftOperand;op.RightOperand=rightOperand;}elseif(operandisUnaryOperator){((UnaryOperator)operand).Operand=expressionStack.Pop();}elseif(operandisFunction){Functionfunction=(Function)operand;for(intargNum=0;argNumcouldbeaduplicateof:Isthereastringmathcalculatorin.NET?简短的回答是没有,长的回答见链接(我推荐'coppercoders'解决方案。)你为什么不使用SimpleMathParser或类似的东西?链接文本在最近的Silverlight应用程序中,我通过使用正则表达式(只是为了安全起见)擦除字符串并将其传递给JavaScript求值器来降低成本。它实际上工作得很好,但我承认这是一个hack。http://josheinstein.com/blog/index.php/2010/03/mathevalconverter以上是C#学习教程:如何解析C#中的数学表达式?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: