评估列表作为数学表达式

发布于 2024-11-30 06:51:59 字数 195 浏览 0 评论 0原文

我有一个充满值和运算符的 List

["123", "+", "(", "890", "-", "15.00", ")"]

我知道我可以制定一种算法,将这些数字和运算符压入堆栈,然后将它们弹出并进行评估。但是,有没有更好的方法来不使用外部库呢?

I have a List<String> that is full of values and operators.

["123", "+", "(", "890", "-", "15.00", ")"]

I know that I can make an algorithm that will push these numbers and and operators onto a stack and pop them off and evaluate as I go. But, is there a better way to do with without using a external library?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

饮湿 2024-12-07 06:51:59

将数字和运算符压入堆栈将是一个解释器。

明显更好的方法(对于“更好”的某些定义)是编写一个编译器!

您已经将输入拆分为词法标记,因此您可以跳过实现词法分析器并可以直接深入构建 AST。您可以在系统中找到合适的类来将输入转换为目标。林克。表达式命名空间;查看表达式类。您可以将结果包装在 lambda 表达式中,将其编译为 IL 并在 CLR 上执行!

Pushing the numbers and operators onto a stack would be an interpreter.

The obvious better way to do this (for some definition of "better") is to write a compiler!

You already have the input split into lexical tokens, so you can skip implementing a lexer and can dive right into building the AST. You can find suitable classes to transform your input to in the System.​Linq.​Expressions Namespace; have a look at the Expression Class. You can wrap the result in a lambda expression, compile it to IL and execute it on the CLR!

晚风撩人 2024-12-07 06:51:59

您可以加入List,然后让编译器在运行时对其进行评估,如 Mehrdad 所说。

Expression e = new Expression("5 * 2"); 
e.Evaluate();

我发现此处已经提出了一个非常类似的问题

更新:

NCalc “NCalc - .NET 数学表达式求值器”,即使这是一个外部库我认为它是一个开源项目,这意味着您可以将代码直接添加到您的项目中。

更新:

您可以使用 String.Join 函数加入列表。

string formula = String.Join("",listMathOperators);

You can join the List and then let the compiler evaluate it at runtime as Mehrdad stated.

Expression e = new Expression("5 * 2"); 
e.Evaluate();

I found a very similar question already asked here

update :

NCalc "NCalc - Mathematical Expressions Evaluator for .NET" even though this is an external library I think it is an open source project which means you can add the code directly to your project.

Update :

You can use the String.Join function to join the List.

string formula = String.Join("",listMathOperators);
記柔刀 2024-12-07 06:51:59

您始终可以使用 .NET 框架中的 C# 编译器类将其计算为 C# 表达式...

You can always use the C# compiler classes in the .NET framework to evaluate it as a C# expression...

情归归情 2024-12-07 06:51:59

我有一个完整的类可以计算任何表达式。

首先,您需要将列表中的所有字符串提取为单个字符串,例如:

string sExpression = "123+(890-15.00)";

其次,您需要在解析器中计算此表达式,我有一个完整的类可以为您完成此操作,但我无法在此处附加文件。

I have a complete class that calculates any expression.

First, you need to extract all strings of your list to a single string, like:

string sExpression = "123+(890-15.00)";

Second, you need to evaluate this expression in a parser, I have a complete class that makes this for you, but I can't attach files here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文