最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用C#代碼計算數(shù)學(xué)表達式實例

 更新時間:2025年01月20日 15:38:51   作者:坐井觀老天  
這段文字主要講述了如何使用C#語言來計算數(shù)學(xué)表達式,該程序通過使用Dictionary保存變量,定義了運算符優(yōu)先級,并實現(xiàn)了EvaluateExpression方法來執(zhí)行表達式計算,該方法通過查找優(yōu)先級最低的運算符來拆分表達式,并遞歸調(diào)用自身來評估子表達式

C#代碼計算數(shù)學(xué)表達式

此程序展示了如何使用 C# 代碼來計算數(shù)學(xué)表達式。

該程序以 以下代碼開始。

此代碼聲明了一個Dictionary,稍后將使用它來保存變量。(例如,如果用戶想要 A = 10、B = 3 和 Pi = 3.14159265。)

然后它定義了一個Precedence枚舉來表示運算符的優(yōu)先級。例如,乘法的優(yōu)先級高于加法。

單擊“Evaluate”按鈕時,程序會復(fù)制您輸入到“ Primatives Dictionary中的任何基元,然后調(diào)用EvaluateExpression方法,該方法會執(zhí)行所有有趣的工作。

該方法很長,因此我將分段描述

// 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 = false;

        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) &&
                            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++)

該方法的這一部分用于查找表達式中優(yōu)先級最低的運算符。為此,它只需循環(huán)遍歷表達式,檢查其運算符字符,并確定它們的優(yōu)先級是否低于先前找到的運算符。

下面的代碼片段顯示了下一步

    // 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) %
                    EvaluateExpression(rexpr);
            case "+":
                return
                    EvaluateExpression(lexpr) +
                    EvaluateExpression(rexpr);
            case "-":
                return
                    EvaluateExpression(lexpr) -
                    EvaluateExpression(rexpr);
        }
    }

如果括號未閉合,該方法將引發(fā)異常。否則,它會使用優(yōu)先級最低的運算符作為分界點,將表達式拆分成多個部分。然后,它會遞歸調(diào)用自身來評估子表達式,并使用適當?shù)牟僮鱽砗喜⒔Y(jié)果。

例如,假設(shè)表達式為 2 * 3 + 4 * 5。那么優(yōu)先級最低的運算符是 +。該函數(shù)將表達式分解為 2 * 3 和 4 * 5,并遞歸調(diào)用自身來計算這些子表達式的值(得到 6 和 20),然后使用加法將結(jié)果合并(得到 26)。

以下代碼顯示該方法如何處理函數(shù)調(diào)用

    // 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 a 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_pos > 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.
            }
        }
    }

此代碼檢查表達式是否以 ( 開頭并以 結(jié)尾。如果是,則刪除這些括號并計算表達式的其余部分。

接下來,代碼確定表達式是否以一元 + 或 - 運算符開頭。如果是,程序?qū)⒂嬎悴粠н\算符的表達式,如果運算符為 -,則對結(jié)果取反。

然后,代碼會查找Sin、CosFactorial等函數(shù)。如果找到,它會調(diào)用該函數(shù)并返回結(jié)果。(下載示例以查看Factorial函數(shù)。)您可以類似地添加其他函數(shù)。

以下代碼顯示了該方法的其余部分

    // 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.");
    }
}

如果表達式仍未求值,則它必須是您在文本框中輸入的原始值或數(shù)值。

代碼將檢查原始字典以查看表達式是否存在。

如果值在字典中,則代碼獲取其值,將其轉(zhuǎn)換為雙精度值,然后返回結(jié)果。

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java 文件下載支持中文名稱的實例

    java 文件下載支持中文名稱的實例

    下面小編就為大家分享一篇java 文件下載支持中文名稱的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • C#實現(xiàn)更改MDI窗體背景顏色的方法

    C#實現(xiàn)更改MDI窗體背景顏色的方法

    這篇文章主要介紹了C#實現(xiàn)更改MDI窗體背景顏色的方法,涉及C#窗體背景色的設(shè)置技巧,非常簡單實用,需要的朋友可以參考下
    2015-08-08
  • C#如何打開選擇文件對話框和選擇目錄對話框

    C#如何打開選擇文件對話框和選擇目錄對話框

    這篇文章主要介紹了C#如何打開選擇文件對話框和選擇目錄對話框問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • C#判別ASCII碼和十六進制的實現(xiàn)方法詳解

    C#判別ASCII碼和十六進制的實現(xiàn)方法詳解

    ASCII碼是一種基于拉丁字母的字符編碼系統(tǒng),十六進制Hexadecimal是計算機領(lǐng)域最常用的數(shù)制表示法,下面我們就來看看如何使用C#判別ASCII碼和十六進制吧
    2026-04-04
  • Unity3D網(wǎng)格功能生成球體網(wǎng)格模型

    Unity3D網(wǎng)格功能生成球體網(wǎng)格模型

    這篇文章主要為大家詳細介紹了Unity3D網(wǎng)格功能生成球體網(wǎng)格模型,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-02-02
  • c# Newtonsoft 六個值得使用的特性(上)

    c# Newtonsoft 六個值得使用的特性(上)

    這篇文章主要介紹了c# Newtonsoft 六個值得使用的特性,文中示例代碼非常詳細,幫助大家更好的理解和學(xué)習,感興趣的朋友可以了解下
    2020-06-06
  • c#隱藏基類方法的作用

    c#隱藏基類方法的作用

    這篇文章主要介紹了c#隱藏基類方法的作用,大家可以參考使用
    2013-12-12
  • Unity Shader實現(xiàn)3D翻頁效果

    Unity Shader實現(xiàn)3D翻頁效果

    這篇文章主要為大家詳細介紹了Unity Shader實現(xiàn)3D翻頁效果,Plane實現(xiàn)翻頁效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • 簡單聊聊C#的線程本地存儲TLS到底是什么

    簡單聊聊C#的線程本地存儲TLS到底是什么

    C#的ThreadStatic是假的,因為C#完全是由CLR(C++)承載的,言外之意C#的線程本地存儲,用的就是用C++運行時提供的 __declspec(thread)或__thread來虛構(gòu)的一套玩法,下面我們就來深入講講C#的線程本地存儲TLS到底是什么吧
    2024-01-01
  • 使用C#合并PDF文檔的實現(xiàn)步驟

    使用C#合并PDF文檔的實現(xiàn)步驟

    在當今的數(shù)字化辦公環(huán)境中,PDF文檔已經(jīng)成為信息交換和存檔的標準格式,然而,在許多業(yè)務(wù)場景中,開發(fā)者會面臨一個共同的需求:將多個PDF文檔合并為一個,本文將深入探討如何利用Spire.PDF for .NET 這一強大的工具,幫助C#開發(fā)者輕松實現(xiàn)PDF文檔的合并,需要的朋友可以參考下
    2025-09-09

最新評論

海淀区| 望都县| 林州市| 本溪市| 景洪市| 招远市| 乐昌市| 天水市| 宝清县| 自贡市| 吉木萨尔县| 吉安市| 淮北市| 开远市| 河西区| 游戏| 梨树县| 赤壁市| 鹤山市| 辽宁省| 奉新县| 温泉县| 象山县| 滁州市| 南川市| 榕江县| 黑水县| 遵义市| 松潘县| 嘉兴市| 寻乌县| 台江县| 钦州市| 武冈市| 高安市| 靖江市| 土默特右旗| 开平市| 永丰县| 白城市| 新和县|