Yêu cầu là phải viết chương trình tính biểu thức dạn hậu tố (ví dụ: 23+4* tức là (2+3)*4 )
Source mình viết đây, nhưng chạy ko đúng mong các bạn giúp. Xin cám ơn nhiều.
<code>
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define max 100
typedef struct{
int top;
char nodes[max];
}stack;
//kiem tra stack full
int Full(stack S)
{
if (S.top==max-1) return 1;
else return 0;
}
//kiem tra stack rong
int Empty(stack S)
{
if (S.top==-1) return 1;
else return 0;
}
//dua phan tu vao stack
void Push(int x, stack &S)
{
if (!Full(S)) S.nodes[++S.top]=x;
else cout<<"Bieu thuc qua dai (can it hon "<<max<<" ky tu)";
}
//lay ptu tu stack
char Pop(stack &S)
{
if(!Empty(S)) return S.nodes[S.top--];
else return '|';
}
void main()
{
clrscr();
stack S;
char bt[100];
int ptu,tinh,so1,so2;
cout<<"Nhap bieu thu dang hau to: ";
cin>>bt;
S.top=-1;
//
for (int i=0;i<strlen(bt);i++)
{
ptu=bt[i];
switch (ptu)
{
case '+':
{
so1=toascii(Pop(S))-toascii('0');
so2=toascii(Pop(S))-toascii('0');
tinh=so1+so2;
Push(tinh,S);
}break;
case '-':
{
so1=toascii(Pop(S))-toascii('0');
so2=toascii(Pop(S))-toascii('0');
tinh=so1-so2;
Push(tinh,S);
}break;
case '*':
{
so1=toascii(Pop(S))-toascii('0');
so2=toascii(Pop(S))-toascii('0');
tinh=so1*so2;
Push(tinh,S);
}break;
case '/':
{
so1=toascii(Pop(S))-toascii('0');
so2=toascii(Pop(S))-toascii('0');
tinh=so1/so2;
Push(tinh,S);
}break;
default:
Push(ptu,S);
}
}
cout<<"Gia tri bieu thuc la: "<<Pop(S);
getch();
}
</code>
Bookmarks