【问题标题】:Evaluate mathematical expression from a string using VB使用 VB 计算字符串中的数学表达式
【发布时间】:2012-11-01 13:58:57
【问题描述】:

我想用VB从一个字符串计算一个算术表达式,有什么想法吗?

例如:文本框中的“x+2”,我想计算表达式

【问题讨论】:

标签: vb.net math


【解决方案1】:
Dim equation As String = "2+6/2"
Dim result = New DataTable().Compute(equation, Nothing)

【讨论】:

  • 这个答案不需要额外的库添加到项目中:)
  • @Andrew 你太棒了...谢谢队友。
【解决方案2】:

您可以为此使用 NCalc。它还接受 x, y, z,...

等参数
Dim e As Expression = new Expression("2 + 3 * 5")
Msgbox(17 = e.Evaluate())

【讨论】:

  • @JohanLarsson 抱歉,我不知道 :(
  • 我认为不是。(不太确定)。
【解决方案3】:

您可以为此目的使用 mxparser 库。通过单击 Microsoft Visual Studio 的添加引用按钮,在您的项目中引用 mxparser.dll。mxparser 库源代码或最新的 dll 文件可以来自 www.mathparser.org。 mXparser 是适用于 Java、Android、C# .NET (CLS) 库的数学解析器。

Imports org.mariuszgromada.math.mxparser
Private Function evaluate(ByVal str As String) AS Double
Dim expr As Expression = New Expression(str)
DIM d1 As Double
d1=0
d1=expr.calculate()
return d1
End Function

对函数的调用可以如下。

DIM str as String
str=""
str=((45^5)/45))*(5*6)

Dim d as Double
d=0
d=evaluate(str)
MsgBox(" The result of the expression is   " + d.ToString)

【讨论】:

猜你喜欢
  • 2015-12-03
  • 2013-09-23
相关资源
最近更新 更多