这是一个实现四则混合运算的代码,包括三个方法,调用时,使用compute()方法即可,这个方法可以用于动态计算。
代码:
string precede(string p, string q)
{
switch(p)
{
case "+":
case "-":
return ("*/(".indexof(q) != -1) ? "<":">";
case "*":
case "/":
return (q == "(") ? "<":">";
case "(":
return (q == ")") ? "=":"<";
case ")":
return (q == "(") ? "?":">";
case "#":
return (q == "#") ? "=":"<";
}
return "?";
}
double operate(double a, char o, double b)
{
switch(o)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return 0;
}
object compute(string expression)
{
stack narr = new stack(), oarr = new stack();
int j = 0;
double a = 0, b = 0;
string w = "";
char o;
matchcollection arr = regex.matches(expression.replace(" ", "") + "#", @"(((?<=(^|/())-)?/d+(/./d+)?|/d)");
oarr.push("#");
w = convert.tostring(arr[j++]);
while(!(w == "#" && convert.tostring(oarr.peek()) == "#"))
{
if("+-*/()#".indexof(w) != -1)
{
switch(precede(oarr.peek().tostring(), w))
{
case "<":
oarr.push(w);
w = convert.tostring(arr[j++]);
break;
case "=":
oarr.pop();
w = convert.tostring(arr[j++]);
break;
case ">":
o = convert.tochar(oarr.pop());
b = convert.todouble(narr.pop());
a = convert.todouble(narr.pop());
narr.push(operate(a, o, b));
break;
default:
return "计算出错!";
}
}
else
{
narr.push(w);
w = convert.tostring(arr[j++]);
}
}
return narr.pop();
}
新闻热点
疑难解答