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

相关文章

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

oracle DBMS_SQL.PARSE的使用方法和示例

《oracleDBMS_SQL.PARSE的使用方法和示例》DBMS_SQL是Oracle数据库中的一个强大包,用于动态构建和执行SQL语句,DBMS_SQL.PARSE过程解析SQL语句或PL/S... 目录语法示例注意事项DBMS_SQL 是 oracle 数据库中的一个强大包,它允许动态地构建和执行

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2

Python如何计算两个不同类型列表的相似度

《Python如何计算两个不同类型列表的相似度》在编程中,经常需要比较两个列表的相似度,尤其是当这两个列表包含不同类型的元素时,下面小编就来讲讲如何使用Python计算两个不同类型列表的相似度吧... 目录摘要引言数字类型相似度欧几里得距离曼哈顿距离字符串类型相似度Levenshtein距离Jaccard相

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Python中顺序结构和循环结构示例代码

《Python中顺序结构和循环结构示例代码》:本文主要介绍Python中的条件语句和循环语句,条件语句用于根据条件执行不同的代码块,循环语句用于重复执行一段代码,文章还详细说明了range函数的使... 目录一、条件语句(1)条件语句的定义(2)条件语句的语法(a)单分支 if(b)双分支 if-else(