亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用C#代碼計算數學表達式實例

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

C#代碼計算數學表達式

此程序展示了如何使用 C# 代碼來計算數學表達式。

該程序以 以下代碼開始。

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

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

單擊“Evaluate”按鈕時,程序會復制您輸入到“ Primatives Dictionary中的任何基元,然后調用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)先級最低的運算符作為分界點,將表達式拆分成多個部分。然后,它會遞歸調用自身來評估子表達式,并使用適當的操作來合并結果。

例如,假設表達式為 2 * 3 + 4 * 5。那么優(yōu)先級最低的運算符是 +。該函數將表達式分解為 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 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.
            }
        }
    }

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

接下來,代碼確定表達式是否以一元 + 或 - 運算符開頭。如果是,程序將計算不帶運算符的表達式,如果運算符為 -,則對結果取反。

然后,代碼會查找Sin、CosFactorial等函數。如果找到,它會調用該函數并返回結果。(下載示例以查看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.");
    }
}

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

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

如果值在字典中,則代碼獲取其值,將其轉換為雙精度值,然后返回結果。

總結

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

相關文章

  • 利用WinForm實現上左右布局的方法詳解

    利用WinForm實現上左右布局的方法詳解

    現在90%的管理系統(tǒng)都是在用上左右這種布局方式,真可謂是經典永流傳。本文將利用WinForm實現上左右布局這一布局效果,感興趣的可以學習一下
    2022-09-09
  • c#中如何去除字符串左邊的0

    c#中如何去除字符串左邊的0

    這篇文章主要介紹了c#中如何去除字符串左邊的0問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • C#實現拷貝文件到另一個文件夾下

    C#實現拷貝文件到另一個文件夾下

    這篇文章主要介紹了C#實現拷貝文件到另一個文件夾下,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • Unity 如何設定 Animator分割播放

    Unity 如何設定 Animator分割播放

    這篇文章主要介紹了Unity 設定 Animator分割播放的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • C# textbox實時輸入值檢測方式

    C# textbox實時輸入值檢測方式

    這篇文章主要介紹了C# textbox實時輸入值檢測方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • C# wpf使用ListBox實現尺子控件的示例代碼

    C# wpf使用ListBox實現尺子控件的示例代碼

    本文主要介紹了C# wpf使用ListBox實現尺子控件的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • C#使用SevenZipSharp實現壓縮文件和目錄

    C#使用SevenZipSharp實現壓縮文件和目錄

    SevenZipSharp壓縮/解壓(.7z?.zip)”是指使用SevenZipSharp庫進行7z和zip格式的文件壓縮與解壓縮操作,SevenZipSharp是C#語言封裝的7-Zip?API,它使得在.NET環(huán)境中調用7-Zip的功能變得簡單易行,本文給大家介紹了C#使用SevenZipSharp實現壓縮文件和目錄
    2025-01-01
  • C# Page用于各頁面繼承功能實例

    C# Page用于各頁面繼承功能實例

    這篇文章主要介紹了C# Page用于各頁面繼承功能實例,包含了常見的頁面視圖、數據緩存、數據庫操作等技巧,需要的朋友可以參考下
    2014-10-10
  • 淺析C#異步中的Overlapped是如何尋址的

    淺析C#異步中的Overlapped是如何尋址的

    用ReadAsync做文件異步讀取時,在Win32層面會傳lpOverlapped到內核層,那在內核層回頭時,它是如何通過這個lpOverlapped尋找到?ReadAsync這個異步的Task的呢,下面我們就來簡單分析一下吧
    2025-01-01
  • C#?List生成Txt文檔并且讀取Txt文檔封裝List

    C#?List生成Txt文檔并且讀取Txt文檔封裝List

    這篇文章主要介紹了C#?List生成Txt文檔并且讀取Txt文檔封裝List,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的朋友可以參考一下
    2022-08-08

最新評論