本文介绍了在c ++中评估后缀表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于某种原因,该程序运行但编译器正在终止并将我发送到调试和终止。
任何想法为什么?我被卡住了。
我在代码中评论了它应该做什么。我可以废弃这一切,只是尝试别的东西,并相信我,我即将哈哈哈哈,但我真的想知道为什么编译器正在把它取回来
For some reason, this program runs but compiler is terminating and sends me to debug and termination.
Any idea why? I'm stuck like chuck.
I commented in the code what it's supposed to do. I can scrap this whole thing and just try something else, and trust me, I'm about to ha ha ha, but I really want to know why the compiler is puking it back out
#include<iostream>
#include<conio.h>
#include<ctype.h>
using namespace std;
/*
The program will evaluate a postfix expression that contains digits and operators.
The program tries to simulate the microprocessor execution stack or evaluation
of expression.
*/
//The class performing the evaluation
class Evaluation {
public:
int st[50];
int top;
char str[50];
Evaluation() {
top = -1;
}
//function to push the item
void push(int item) {
top++;
st[top] = item;
}
//function to pop an item
int pop() {
int item = st[top];
top--;
return item;
}
//function to perform the operation depending on the operator.
int operation(int a,int b,char opr) {
switch(opr) {
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
default: return 0;
}
}
int calculatePostfix();
};
//This is the function that calculates the result of postfix expression.
int Evaluation::calculatePostfix() {
int index = 0;
while(str[index]!='#') {
if(isdigit(str[index])) {
push(str[index]-'0');
}
else {
int x = pop();
int y = pop();
int result = operation(x,y,str[index]);
push(result);
}
index++;
}
return pop();
}
/*
main function that reads the postfix expression and that prints the result.
The input expression should be ending with a number
An example input expression would be:
123*+
Its output will be 7.
*/
int main() {
void clrscr();
Evaluation eval;
cout << "Enter the postfix: ";
cin >> eval.str;
int result = eval.calculatePostfix();
cout << "the result is " << result;
getch();
}
推荐答案
while(str[index]!='#') {
表示它会循环遍历 str
,直到找到#,如果字符串中没有,那么它将失败。
尝试输入此内容;
means it will loop over str
until it finds a #, if that is not present in the string then it will fail.
Try inputting this;
123*+#
希望这会有所帮助,
Fredrik
Hope this helps,
Fredrik
这篇关于在c ++中评估后缀表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!