下面我試圖編寫一個評估後綴表達式的程序。但是,我注意到,我設置的兩個要素未被設置爲正確的值。我仍然在學習C++庫中的堆棧特性,所以如果有人能解釋爲什麼會發生這種情況,我將不勝感激!評價後綴函數
/*Sample output:
Enter an infix or prefix expression:3+4-1
Postfix is: 34+1-
postFix[i]: 3
postFix[i]: 4
element1: 52
element2: 51
val is: 103
postFix[i]: 1
element1: 49
element2: 103
val is: 54
Value is 54*/
int evaluatePostfix (string postFix)
{
stack<int> operands;
int length = postFix.length();
int val = 0;
for (int i = 0; i < length; i++)
{
//if the char is a digit push the digit onto the stack
if(isdigit(postFix[i]))
{
operands.push(postFix[i]);
cout << "postFix[i]: " << postFix[i] << endl;
}
else if (isOperator(postFix[i]))
{
//
//element 1 and element 2 will be the element on the top of the stack
//
int element1 = operands.top();
cout << "element1: " << element1 << endl;
operands.pop();
int element2 = operands.top();
cout << "element2: " << element2 << endl;
operands.pop();
//
//create a switch statement that evaluates the elements based on the operator
//
switch(postFix[i])
{
case '+':
val = element2 + element1;
cout << "val is: " << val << endl;
operands.push(val);
break;
case '-':
val = element2 - element1;
cout << "val is: " << val << endl;
operands.push(val);
break;
case '*':
val = element2 * element1;
operands.push(val);
break;
case '/':
val = element2/element1;
operands.push(val);
break;
default:
return 0;
}
}
}
return val;
}
你能給一個堅實的例子嗎?例如,我推3,但它彈出42. – ChiefTwoPencils
我認爲這是這裏的問題。我將這些元素放在堆棧上,但是我推入堆棧的元素並不是被彈出的元素。因此,例如,我按3和4.然後,程序看到操作符'+',並決定彈出頂部的兩個元素,它們應該是3和4,但它會彈出52和51等隨機數。我不知道它爲什麼這樣做 –