J'ai déjà trouvé différentes solutions sur Stackoverflow, mais il y avait des choses que je ne comprenais pas. Quelle est la meilleure méthode pour calculer la sortie de, par exemple: ((1+ (4 * (2 + 3))) + ((2 + 3) * (4 * 5)))?Comment calculer la sortie d'Infix-Expression en utilisant des piles en C#
Ma méthode semble que suivant, mais je sais qu'il ya beaucoup d'erreurs dans ce:
public static int ComputeInfix(string infix) {
Stack<char> operatorstack = new Stack<char>();
Stack<int> operandstack = new Stack<int>();
for(int j = 0; j < infix.Length; j++) {
char c = infix[j];
if (c => 0 && c <= 9) {
operandstack.Push(c);
}
else if ((c == '+' || c == '*' || c == '/' || c == '-')) {
if (operatorstack.IsEmpty()) {
operatorstack.Push(c);
}
else {
if (operatorstack.Peek() != '*' || operatorstack.Peek() != '/') {
operatorstack.Push(c);
}
}
}
else if (c == '(') {
operatorstack.Push(c);
}
else if (c == ')') {
operatorstack.Pop();
}
}
return infix;
}
changé à:
Stack<char> operatorstack = new Stack<char>();
Stack<char> operandstack = new Stack<char>();
for(int j = 0; j < infix.Length; j++) {
char c = infix[j];
if (c => '0' && c <= '9') {
operandstack.Push(c);
}
Mais obtenir l'erreur:
Infix.cs(16,8): error CS0136: A local variable named
c' cannot be declared in this scope because it would give a different meaning to
c', which is already used in a `parent or current' scope to denote something else
[Calculator.net?](http://weblogs.asp.net/pwelter34/archive/2007/05/05/calculator-net-calculator-that-evaluates-math-expressions.aspx) – PoweredByOrange
Maintenant modifié à: '(c => '0' && c <= '9')' – Patzi0207
La ligne 'c => 0 && c <= 9' est fausse. La variable 'c' est un char. Si vous voulez le nombre entier de ce char, vous devez l'analyser, comme ceci 'int nombre = int.Parse (c.ToString());' –