使用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

相关文章

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

C#读写文本文件的多种方式详解

《C#读写文本文件的多种方式详解》这篇文章主要为大家详细介绍了C#中各种常用的文件读写方式,包括文本文件,二进制文件、CSV文件、JSON文件等,有需要的小伙伴可以参考一下... 目录一、文本文件读写1. 使用 File 类的静态方法2. 使用 StreamReader 和 StreamWriter二、二进

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

C#中Guid类使用小结

《C#中Guid类使用小结》本文主要介绍了C#中Guid类用于生成和操作128位的唯一标识符,用于数据库主键及分布式系统,支持通过NewGuid、Parse等方法生成,感兴趣的可以了解一下... 目录前言一、什么是 Guid二、生成 Guid1. 使用 Guid.NewGuid() 方法2. 从字符串创建

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注