使用C#代碼計算數學表達式實例
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
、Cos
和Factorial
等函數。如果找到,它會調用該函數并返回結果。(下載示例以查看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."); } }
如果表達式仍未求值,則它必須是您在文本框中輸入的原始值或數值。
代碼將檢查原始字典以查看表達式是否存在。
如果值在字典中,則代碼獲取其值,將其轉換為雙精度值,然后返回結果。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。