[英]How can I accept negative values in Postfix and Infix Notation?
我已經為計算器編寫了一些方法。 一個用於評估輸入的Postfix表達式,另一個用於將輸入的中綴表達式轉換為后綴表達式。
這兩種方法都允許多位數整數以及數字輸入類型的浮點數。
現在我的問題:
我想在這兩種方法中加入負輸入,例如Infix:“3 *( - 1)”。
但是,我對如何實現這個問題缺乏了解。 也許有人可以給我一些想法或代碼示例。
我在下面列出了兩種方法。 它們中使用了一些簡單的方法,這里沒有顯示,但大多數函數名稱都應該很好地解釋它們。 由於這個事實,我把它們留在了外面,以盡可能縮短時間。
string InfixToPostfix(string expression)
{
string postfix = "";
stack <char> S;
for (int i = 0; i < expression.length(); i++)
{
if (expression[i] == ' ') continue; // Falls leerzeichen oder ',' gefunden mit nächster Iteration weiter machen
else if (IsOperator(expression[i])) // Falls ein Operator gefunden wurde:
{
while (!S.empty() && S.top() != '(' && HasHigherPrecedence(S.top(), expression[i])) // Wenn Operator auf Stack höhere Precedence hat, dann diesen an String anhängen und vom Stack nehmen
{
postfix += S.top();
postfix += ' ';
S.pop();
}
S.push(expression[i]); // Wenn Operator die Bedingungen in der while Schleife nicht erfüllt diesen auf Stack legen
}
else if (isDigit(expression[i]) || isComma(expression[i])) //Wenn ein Digit gefunden wurde diesen an String anhängen
{
postfix += expression[i];
if (i+1 >= expression.length() || (!isDigit(expression[i + 1]) && !isComma(expression[i+1]))) //Wenn die nächste Zahl kein Digit ist, dann leerzeichne an String anhängen
{
postfix += ' ';
}
}
else if (expression[i] == '(') // '(' wird auf Stack gepusht
{
S.push(expression[i]);
}
else if (expression[i] == ')') // Wenn ')' gefunden wird, dann:
{
while (!S.empty() && S.top() != '(') // Sofern Stack nicht leer und das oberste Element des Stacks nicht eine Klammer auf ist wird das oberste Element des Stacks dem String angehängt
{
postfix += S.top();
S.pop();
}
S.pop(); //ansonsten wird '(' einfach vom Stack genommen
}
}
while (!S.empty()) // Am Ende der Expression werden alle verbleibenden Elemente vom Stack genommen und Leerzeichen eingefügt
{
postfix += S.top();
postfix += ' ';
S.pop();
}
return postfix; // Rückgabe der jetzt in Postfix vorliegenden Expression
}
//Löst eine Aufgabe in Postfix Notation
float EvaluatePostfix(string expression)
{
stack<float> S;
float j;
for (int i = 0; i< expression.length(); i++) {
if (expression[i] == ' ') continue; // wenn leer oder ',' mit nächster iteration weiter machen
else if (IsOperator(expression[i])) { //Wenn Operator nehme die Operanden vom Stack und wende den Operator an
float operand2 = S.top();
S.pop();
float operand1 = S.top();
S.pop();
float result = PerformOperation(expression[i], operand1, operand2);
S.push(result); //Das Ergebnis zurück auf Stack legen
}
else if (isDigit(expression[i]))
{
float operand = 0;
while (i<expression.length() && isDigit(expression[i]))
{
operand = (operand * 10) + (expression[i] - '0'); //wenn rechts einer Zahl eine weitere Zahl steht, kann operand mal 10 genommen werden und die rechts stehende zahl addiert werden
i++;
}
if (i < expression.length() && isComma(expression[i]))
{
j = 1.0;
i++;
while (i < expression.length() && isDigit(expression[i]))
{
operand = operand + ((expression[i] - '0') / pow(10.0, j));
i++;
j++;
}
}
i--; //Verhindert einen Skip des Operators, i wird sowohl in der while schleife als auch im for hochgezählt
S.push(operand); //Der Operand wird auf den Stack gepusht
}
}
return S.top(); //Stack sollte ein element besitzen, somit ist dies das Ergebnis
}
我沒有完整的解決方案,但這里有幾個提示。
我建議在嘗試理解操作順序之前插入一個讀取字符並生成標記的抽象層。 表達式“(42 + 1) - -3”將成為列表{'(',42,'+',1,')',' - ',' - ',3}。 令牌通常實現為具有類型枚舉(例如,OPERATOR或NUMBER)和值(例如,char或float)的類。 (高級:然后你可以將你的標記轉換為表達式樹,但這里可能沒有必要。)這是一個更多的工作,但它比直接字符串解析更容易理解。
完成后,關鍵是確定' - '符號是作為中綴減法還是作為前綴否定。 為此,請查看上一個標記(如果有)。 如果它是表達式終止符,如')'或數字,則為中綴減法。 如果沒有這樣的令牌,或者它是其他令牌,則它的前綴為否定。
這就是我做的:
class expression
{
//constructors and destructors
public:
expression();
~expression();
//member properties
private:
std::string expr;
std::string postfixExpr;
//member methods
public:
// accepts the expression from the user
void input();
//prints the accepted expression
void output();
//evaluates the accepted expression
float eval();
//converts infix expression to postfix
void convertToPostfix();
friend bool isOperator(char);
};
inline bool isOperator(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')' || c == '#')
return true;
return false;
}
void expression::input()
{
std::cin >> this->expr;
}
float expression::eval()
{
std::stack<float> s;
float op1, op2;
for (int i = 0; i < expr.length(); i++)
{
if (expr[i] == '(')
{
float sum = 0;
bool flag = false;
while (expr[++i] != ')')
{
if (expr[i] == '-') {
flag = true;
i++;
}
sum = sum * 10.0 + (float(expr[i]) - float('0'));
}
if (flag)
sum = -sum;
s.push(sum);
continue;
}
else if (!isOperator(expr[i]))
{
s.push(float(expr[i]) - float('0'));
}
else
{
op2 = s.top();
s.pop();
op1 = s.top();
s.pop();
switch (expr[i])
{
case '+':
s.push(op1 + op2);
break;
case '-':
s.push(op1 - op2);
break;
case'*':
s.push(op1*op2);
break;
case '/':
s.push(op1 / op2);
break;
default:
std::cerr << "Wrong operator" << std::endl;
return 0;
}
}
}
return s.top();
}
在我的實現中,唯一的障礙是使用'('和')'作為分隔符。 其次,我還將std :: string expr作為我的表達式類中的屬性。 這很好用。 但請注意,請在后綴表示法中輸入您的表達式,因為我仍然必須包含convertToPostfix函數。 但我想,你會自己想出來的:)
快樂編碼:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.