评估算术表达式而不评估变量。 [英] Evaluates arithmetic expression without evaluating variables.

查看:66
本文介绍了评估算术表达式而不评估变量。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个用于评估表达式的API。它表达式像100 + 200 + Var1并返回为300 + var1而不评估变量,因为变量值未知。



但是当我试图评估时表达式如100 + var1 + 200我只能返回100 + var1 + 200但不能返回300 + var1。



有什么例子吗评估算术表达式而不评估

变量。



我尝试过:



我搜索了谷歌并找到了NCalc - 用于.NET的数学表达式评估器来评估带变量的算术表达式,但它在运行之前需要这些变量的值

。 div class =h2_lin>解决方案

您需要开始查看运营商关联性 - 维基百科,免费的百科全书 [ ^ ]

+都是lef t-和right-associative,所以 a + b + c 可以按任何顺序进行评估,因此你的评估者可以自由地给每个人分配一个固定/变量值表达式的一部分并将其重新排列为分组固定和可变部分:

 100 + var1 + 200 
F + V + F
因此:
100 + 200 + var1
F + F + V
等价



你在代码中的确如何做到这一点我不能说:我不知道它是如何运作的。但是考虑为您的运算符添加一个关联属性,它应该为您提供所需的开头。


I created a API to evaluate an expression. It takes expression like "100+200+Var1" and return as "300+var1" without evaluating variables since variable value not known.

But when i tried to evaluate expression like "100+var1+200" i can only return as "100+var1+200" but not "300+var1".

Is there any example which evaluates arithmetic expression without evaluating
variables.

What I have tried:

I searched google and found "NCalc - Mathematical Expressions Evaluator for .NET" to evaluate arithmetic expression with variables but it expects values for those variables
before running it.

解决方案

You need to start looking at Operator associativity - Wikipedia, the free encyclopedia[^]
"+" is both left- and right- associative, so a + b + c can be evaluated in any order, so your evaluator would be free to assign a "fixed/variable" value to each part of the expression and rearrange it to "group" the fixed and variable parts:

100 + var1 + 200
 F  +  V   +  F
therefore:
100 + 200 + var1
 F  +  F  +  V
is equivalent


Exactly how you do that in your code I can't say: I have no idea of how it works. But consider adding an associativity property to your operators, and it should give you the beginnings of what you want.


这篇关于评估算术表达式而不评估变量。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆