c# - 公式和数学表达式解析器算法

标签 c# algorithm math

我必须编写一个能够解析公式的程序。 它应该像下面这个例子一样工作:

输入:5x + 7 ^ sin(z)/2T + 44
输出:输入 x、z、t 的值
输入 : 2 , 1 ,2
输出:答案是:一些东西


它应该支持 (+ , * , - , ^ , % , SIN , COS)
我读过this关于调车场算法的页面

而且我还知道如何将中缀表达式转换为后缀或前缀。
这是我的算法:

1 - Give the expression.
2 - If parentheses are balance go to step 3 else show error go to step 1
3 - Find all variables apart from (SIN , COS)
4 - Give variables from input
5 - Replace variables
6 - Prefix the expression and calculate it
7 - Display result in output and close program

是吗?我想用 C# 实现它
请给我建议任何可能对我有用的注释。

最佳答案

如果您决定从头开始编写,您的算法看起来不错。我将提供一些我的想法。

您可能希望将第 5 步(替换变量)移至第 6 步(为表达式添加前缀并进行计算)。换句话说,不是仅仅对变量进行文本查找和替换,而是在需要评估变量的计算过程中进行。这可能会在以后打开更多的可能性,可能使绘制函数图形或具有依赖于其他变量的值的变量变得更容易。不过,您的方法应该适用于简单的情况。

sin 的可能实现和 cos功能,使将来更容易定义其他功能,可能有一个 Dictionary<string, Func<double,double>> ,类似于:

private var functions = 
    new Dictionary<string, Func<double,double>>(StringComparer.OrdinalIgnoreCase)
    {
        { "sin", Math.Sin },
        { "cos", Math.Cos },
        { "sec", Secant }
    };

. . . 

// checking whether a token is a defined function or a variable
if (functions.ContainsKey(token))
{
    // determine the value of the argument to the function
    double inputValue = getArgument();
    double result = functions[token](inputValue);
    . . .
}

. . .

private static double Secant(double x)
{
    return 1.0 / Math.Cos(x);
}

关于c# - 公式和数学表达式解析器算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5753662/

相关文章:

math - 尝试理解 WebGL 中透视矩阵背后的数学原理

java - 是否有超过一个的帖子增量?

c# - 如何在 SQL 中检索给定 StoredProcedure 参数的 .NET 类型?

c# - SerializedProperty 在 Unity3D PropertyDrawers 中始终为 null

c# - 为 Entity Framework 构建自定义表达式 (LINQ)

algorithm - 政党排名-面试解决方案

math - OpenOffice 公式渲染器的独立库?

c# - Thread.Sleep 的问题

python - 重构以计算排序算法的运行时间 - python

python - 尝试使用 python 计算斐波那契数的最后一位时出现错误 "RuntimeWarning: overflow encountered in long_scalars"