使用C#代碼計(jì)算數(shù)學(xué)表達(dá)式實(shí)例
C#代碼計(jì)算數(shù)學(xué)表達(dá)式
此程序展示了如何使用 C# 代碼來(lái)計(jì)算數(shù)學(xué)表達(dá)式。
該程序以 以下代碼開(kāi)始。
此代碼聲明了一個(gè)Dictionary
,稍后將使用它來(lái)保存變量。(例如,如果用戶想要 A = 10、B = 3 和 Pi = 3.14159265。)
然后它定義了一個(gè)Precedence
枚舉來(lái)表示運(yùn)算符的優(yōu)先級(jí)。例如,乘法的優(yōu)先級(jí)高于加法。
單擊“Evaluate”按鈕時(shí),程序會(huì)復(fù)制您輸入到“ Primatives Dictionary
”中的任何基元,然后調(diào)用EvaluateExpression
方法,該方法會(huì)執(zhí)行所有有趣的工作。
該方法很長(zhǎng),因此我將分段描述
// 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++)
該方法的這一部分用于查找表達(dá)式中優(yōu)先級(jí)最低的運(yùn)算符。為此,它只需循環(huán)遍歷表達(dá)式,檢查其運(yùn)算符字符,并確定它們的優(yōu)先級(jí)是否低于先前找到的運(yùn)算符。
下面的代碼片段顯示了下一步
// 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); } }
如果括號(hào)未閉合,該方法將引發(fā)異常。否則,它會(huì)使用優(yōu)先級(jí)最低的運(yùn)算符作為分界點(diǎn),將表達(dá)式拆分成多個(gè)部分。然后,它會(huì)遞歸調(diào)用自身來(lái)評(píng)估子表達(dá)式,并使用適當(dāng)?shù)牟僮鱽?lái)合并結(jié)果。
例如,假設(shè)表達(dá)式為 2 * 3 + 4 * 5。那么優(yōu)先級(jí)最低的運(yùn)算符是 +。該函數(shù)將表達(dá)式分解為 2 * 3 和 4 * 5,并遞歸調(diào)用自身來(lái)計(jì)算這些子表達(dá)式的值(得到 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. } } }
此代碼檢查表達(dá)式是否以 ( 開(kāi)頭并以 結(jié)尾。如果是,則刪除這些括號(hào)并計(jì)算表達(dá)式的其余部分。
接下來(lái),代碼確定表達(dá)式是否以一元 + 或 - 運(yùn)算符開(kāi)頭。如果是,程序?qū)⒂?jì)算不帶運(yùn)算符的表達(dá)式,如果運(yùn)算符為 -,則對(duì)結(jié)果取反。
然后,代碼會(huì)查找Sin
、Cos
和Factorial
等函數(shù)。如果找到,它會(huì)調(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."); } }
如果表達(dá)式仍未求值,則它必須是您在文本框中輸入的原始值或數(shù)值。
代碼將檢查原始字典以查看表達(dá)式是否存在。
如果值在字典中,則代碼獲取其值,將其轉(zhuǎn)換為雙精度值,然后返回結(jié)果。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
利用WinForm實(shí)現(xiàn)上左右布局的方法詳解
現(xiàn)在90%的管理系統(tǒng)都是在用上左右這種布局方式,真可謂是經(jīng)典永流傳。本文將利用WinForm實(shí)現(xiàn)上左右布局這一布局效果,感興趣的可以學(xué)習(xí)一下2022-09-09C#實(shí)現(xiàn)拷貝文件到另一個(gè)文件夾下
這篇文章主要介紹了C#實(shí)現(xiàn)拷貝文件到另一個(gè)文件夾下,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01C# textbox實(shí)時(shí)輸入值檢測(cè)方式
這篇文章主要介紹了C# textbox實(shí)時(shí)輸入值檢測(cè)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07C# wpf使用ListBox實(shí)現(xiàn)尺子控件的示例代碼
本文主要介紹了C# wpf使用ListBox實(shí)現(xiàn)尺子控件的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07C#使用SevenZipSharp實(shí)現(xiàn)壓縮文件和目錄
SevenZipSharp壓縮/解壓(.7z?.zip)”是指使用SevenZipSharp庫(kù)進(jìn)行7z和zip格式的文件壓縮與解壓縮操作,SevenZipSharp是C#語(yǔ)言封裝的7-Zip?API,它使得在.NET環(huán)境中調(diào)用7-Zip的功能變得簡(jiǎn)單易行,本文給大家介紹了C#使用SevenZipSharp實(shí)現(xiàn)壓縮文件和目錄2025-01-01