【问题标题】:operator precedence calculation and RegEx运算符优先级计算和 RegEx
【发布时间】:2014-01-30 10:26:34
【问题描述】:

我想寻求帮助以找出运算符优先级计算的逻辑.. 目前我有这样的代码,它只能计算带有 "+""-" 符号的表达式。

string s = "100 + 50 -2*5*3";
string[] ss = new string[20];
ss = Regex.Split(s, "\\+|-|\\*");
MatchCollection sig = Regex.Matches(s, "\\+|-|\\*");
int x = int.Parse(ss[0]);

for (int i = 1; i < ss.Length; i++)
{
    if (sig[i - 1].ToString() == "+")
        x += int.Parse(ss[i]);
    else if (sig[i - 1].ToString() == "-") 
        x -= int.Parse(ss[i]);
} 

label1.Text = x.ToString();

所以现在在计算表达式时 100 + 50 - 2 * 5 * 3 我得到 148。 我怎样才能使计算出 "*""/" 符号?

【问题讨论】:

标签: c# regex calculator operator-precedence


【解决方案1】:

如果您想以与开始时相同的方式继续:

你必须在尽可能多的时间内计算它,因为你有不同的符号优先级,并且在每次计算后你替换原始序列中的新值,然后用较低优先级的符号再次执行。

original := "100+50-2*5*3"
precedance := {*, /, +, -}

for each precedance => P
    while there is a sub-calculation using P => C
        C := first sub-calculation using P
        compute C
        replace C in original
    enf for
end for

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2020-03-05
    • 1970-01-01
    • 2020-06-23
    • 2023-03-07
    • 2013-05-26
    • 2021-03-29
    • 2013-07-31
    相关资源
    最近更新 更多