使用C#代码计算数学表达式实例

2025-01-21 04:50

本文主要是介绍使用C#代码计算数学表达式实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用C#代码计算数学表达式实例》这段文字主要讲述了如何使用C#语言来计算数学表达式,该程序通过使用Dictionary保存变量,定义了运算符优先级,并实现了EvaluateExpression方法来...

C#代码计算数学表达式

此程序展示了如何使用 C# 代码来计算数学表达式。

该程序以 以下代码开始。

使用C#代码计算数学表达式实例

此代码声明了一个Dictionary,稍后将使用它来保存变量。(例如,如果用户想要 A = 10、B = 3 和 Pi = 3.14159265。)

然后它定义了一个Precedence枚举来表示运算符的优先级。例如,乘法的优先级高于加法。

单击“EvaLuate”按钮时,程序会复制您输入到“ Primatives Dictionary中的任何基元,然后调用EvaluateExpression方法,该方法会执行所有有趣的工作。

该方法很长,因此我将分段描述

// Stores user-entered primitives like X = 10.
private Dictionary<string, string> Primatives;

private enum Precedence
{
    None = 11,
    Unary = 10,     // Not actually used.
    Power = 9,      // We use ^ to mean exponentiation.
    Times = 8,
    Div = 7,
    Modulus = 6,
    Plus = 5,
}
// Evaluate the expression.
private double EvaluateExpression(string expression)
{
    int best_pos = 0;
    int parens = 0;

    // Remove all spaces.
    string expr = expression.Replace(" ", "");
    int expr_len = expr.Length;
    if (expr_len == 0) return 0;

    // If we find + or - now, then it's a unary operator.
    bool is_unary = true;

    // So far we have nothing.
    Precedence best_prec = Precedence.None;

    // Find the operator with the lowest precedence.
    // Look for places where there are no open
    // parentheses.
    for (int pos = 0; pos < expr_len; pos++)
    {
        // Examine the next character.
        string ch = expr.Substring(pos, 1);

        // Assume we will not find an operator. In
        // that case, the next operator will not
        // be unary.
        bool next_unary = pythonfalse;

        if (ch == " ")
        {
            // Just skip spaces. We keep them here
            // to make the error messages easier to
        }
        else if (ch == "(")
        {
            // Increase the open parentheses count.
            parens += 1;

            // A + or - after "(" is unary.
            next_unary = true;
        }
        else if (ch == ")")
        {
            // Decrease the open parentheses count.
            parens -= 1;

            // An operator after ")" is not unary.
            next_unary = false;

            // if parens < 0, too many )'s.
            if (parens < 0)
                throw new FormatException(
                    "Too many close parentheses in '" +
                    expression + "'");
            }
        else if (parens == 0)
        {
            // See if this is an operator.
            if ((ch == "^") || (ch == "*") ||
                (ch == "/") || (ch == "\\") ||
                (ch == "%") || (ch == "+") ||
                (ch == "-"))
            {
                // An operator after an operator
                // is unary.
                next_unary = true;

                // See if this operator has higher
                // precedence than the current one.
                switch (ch)
                {
                    case "^":
                        if (best_prec >= Precedence.Power)
                        {
                            best_prec = Precedence.Power;
                            best_pos = pos;
                        }
                        break;

                    case "*":
                    case "/":
                        if (best_prec >= Precedence.Times)
                        {
                            best_prec = Precedence.Times;
                            best_pos = pos;
                        }
                        break;

                    case "%":
                        if (best_prec >= Precedence.Modulus)
                        {
                            best_prec = Precedence.Modulus;
                            best_pos = pos;
                        }
                        break;

                    case "+":
                    case "-":
                        // Ignore unary operators
                        // for now.
                        if ((!is_unary) &&
  www.chinasem.cn                          best_prec >= Precedence.Plus)
                        {
                            best_prec = Precedence.Plus;
                            best_pos = pos;
                        }
                        break;
                } // End switch (ch)
            } // End if this is an operator.
        } // else if (parens == 0)

        is_unary = next_unary;
    } // for (int pos = 0; pos < expr_len; pos++)

该方法的这一部分用于查找表达式中优先级最低的运算符。为此,它只需循环遍历表达式,检查其运算符字符,并确定它们的优先级是否低于先前找到的运算符。

下面的代码片段显示了下一步

    // If the parentheses count is not zero,
    // there's a ) missing.
    if (parens != 0)
    {
        throw new FormatException(
            "Missing close parenthesis in '" +
            expression + "'");
    }

    // Hopefully we have the operator.
    if (best_prec < Precedence.None)
    {
        string lexpr = expr.Substring(0, best_pos);
        string rexpr = expr.Substring(best_pos + 1);
        switch (expr.Substring(best_pos, 1))
        {
            case "^":
                return Math.Pow(
                    EvaluateExpression(lexpr),
                    EvaluateExpression(rexpr));
            case "*":
                return
                    EvaluateExpression(lexpr) *
                    EvaluateExpression(rexpr);
            case "/":
                return
                    EvaluateExpression(lexpr) /
                    EvaluateExpression(rexpr);
            case "%":
                return
                    EvaluateExpression(lexpr) %
                    Evaluatewww.chinasem.cnExpression(rexpr);
            case "+":
                return
                    EvaluateExpression(lexpr) +
                    EvaluateExpression(rexpr);
            case "-":
                return
                    EvaluateExpression(lexpr) -
                    EvaluateExpression(rexpr);
        }
    }

如果括号未闭合,该方法将引发异常。否则,它会使用优先级最低的运算符作为分界点,将表达式拆分成多个部分。然后,它会递归调用自身来评估子表达式,并使用适当的操作来合并结果。

例如,假设表达式为 2 * 3 + 4 * 5。那么优先级最低的运算符是 +。该函数将表达式分解为 2 * 3 和 4 * 5,并递归调用自身来计算这些子表达式的值(得到 6 和 20),然后使用加法将结果合并(得到 26)。

以下代码显示该方法如何处理函数调用

    // if we do not yet have an operator, there
    // are several possibilities:
    //
    // 1. expr is (expr2) for some expr2.
    // 2. expr is -expr2 or +expr2 for some expr2.
    // 3. expr is Fun(expr2) for a function Fun.
    // 4. expr is ajs primitive.
    // 5. It's a literal like "3.14159".

    // Look for (expr2).
    if (expr.StartsWith("(") & expr.EndsWith(")"))
    {
        // Remove the parentheses.
        return EvaluateExpression(expr.Substring(1, expr_len - 2));
    }

    // Look for -expr2.
    if (expr.StartsWith("-"))
    {
        return -EvaluateExpression(expr.Substring(1));
    }

    // Look for +expr2.
    if (expr.StartsWith("+"))
    {
        return EvaluateExpression(expr.Substring(1));
    }

    // Look for Fun(expr2).
    if (expr_len > 5 & expr.EndsWith(")"))
    {
        // Find the first (.
        int paren_pos = expr.IndexOf("(");
        if (paren_poshttp://www.chinasem.cn > 0)
        {
            // See what the function is.
            string lexpr = expr.Substring(0, paren_pos);
            string rexpr = expr.Substring(paren_pos + 1,
                expr_len - paren_pos - 2);
            switch (lexpr.ToLower())
            {
                case "sin":
                    return Math.Sin(EvaluateExpression(rexpr));
                case "cos":
                    return Math.Cos(EvaluateExpression(rexpr));
                case "tan":
                    return Math.Tan(EvaluateExpression(rexpr));
                case "sqrt":
                    return Math.Sqrt(EvaluateExpression(rexpr));
                case "factorial":
                    return Factorial(EvaluateExpression(rexpr));
                // Add other functions (including
                // program-defined functions) here.
            }
        }
    }

此代码检查表达式是否以 ( 开头并以 结尾。如果是,则删除这些括号并计算表达式的其余部分。

接下来,代码确定表达式是否以一元 + 或 - 运算符开头。如果是,程序将计算不带运算符的表达式,如果运算符为 -,则对结果取反。

然后,代码会查找SinCosFactorial等函数。如果找到,它会调用该函数并返回结果。(下载示例以查看Factorial函数。)您可以类似地添加其他函数。

以下代码显示了该方法的其余部分

    // See if it's a primitive.
    if (Primatives.ContainsKey(expr))
    {
        // Return the corresponding value,
        // converted into a Double.
        try
        {
            // Try to convert the expression into a value.
            return double.Parse(Primatives[expr]);
        }
        catch (Exception)
        {
            throw new FormatException(
                "Primative '" + expr +
                "' has value '" +
                Primatives[expr] +
                "' which is not a Double.");
        }
    }

    // It must be a literal like "2.71828".
    try
    {
        // Try to convert the expression into a Double.
        return double.Parse(expr);
    }
    catch (Exception)
    {
        throw new FormatException(
            "Error evaluating '" + expression +
            "' as a constant.");
    }
}

如果表达式仍未求值,则它必须是您在文本框中输入的原始值或数值。

代码将检查原始字典以查看表达式是否存在。

如果值在字典中,则代码获取其值,将其转换为双精度值,然后返回结果。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持China编程(www.chinasem.cn)。

这篇关于使用C#代码计算数学表达式实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153154

相关文章

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL中比较运算符的具体使用

《MySQL中比较运算符的具体使用》本文介绍了SQL中常用的符号类型和非符号类型运算符,符号类型运算符包括等于(=)、安全等于(=)、不等于(/!=)、大小比较(,=,,=)等,感兴趣的可以了解一下... 目录符号类型运算符1. 等于运算符=2. 安全等于运算符<=>3. 不等于运算符<>或!=4. 小于运

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

MySQL进行数据库审计的详细步骤和示例代码

《MySQL进行数据库审计的详细步骤和示例代码》数据库审计通过触发器、内置功能及第三方工具记录和监控数据库活动,确保安全、完整与合规,Java代码实现自动化日志记录,整合分析系统提升监控效率,本文给大... 目录一、数据库审计的基本概念二、使用触发器进行数据库审计1. 创建审计表2. 创建触发器三、Java

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)