Mình chạy hàm chuyển infix -> postfix thì bình thường nhưng khi gọi hàm tính biểu thức thì bị báo lỗi ở hàm push không biết tại sao nữa. Bạn nào check giùm mình với.
Cho mình hỏi thêm là có cách nào để cải tiến thuật toán cho nó tính được cái biêu thức chứa các toán hạng có nhiều chử số hay không? vd: 31*40+(16+6). Cảm ơn!
Mã:
#include <iostream>
#include <string>
using namespace std;
#define MAX 100
template<class T>
struct STACK{
int top;
T a[MAX];
};
void initialize(STACK<char> &stack)
{
stack.top = 0;
}
template<class T>
bool IsEmpty(STACK<T> stack)
{
if (stack.top == 0)
return true;
return false;
}
template<class T>
bool IsFull(STACK<T> stack)
{
if (stack.top == MAX)
return true;
return false;
}
template<class T>
bool push(STACK<T> &stack, T x)
{
if ( !IsFull(stack) ){
stack.a[stack.top] = x;
stack.top++;
return true;
}
return false;
}
template<class T>
T pop(STACK<T> &stack)
{
if ( !IsEmpty(stack) ){
stack.top--;
return stack.a[stack.top];
}
return NULL;
}
template<class T>
T getTop(STACK<T> stack)
{
if ( !IsEmpty(stack) )
return stack.a[stack.top-1];
return NULL;
}
bool isOperator(char ch){
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
return true;
return false;
}
bool Rank(char x){
if(x == '*' || x == '/') return 2;
if(x == '+' || x == '-') return 1;
return 0;
}
//chuyen infix ---> postfix
string infix2postfix(string infix){
string postfix = "";
STACK<char> s;
initialize(s);
int n = infix.length();
for(int i=0;i<n;i++){
char x = infix[i];
if(!isOperator(x) && x != '(' && x != ')')
postfix += x;
else if(x == '(') push(s,x);
else if(x == ')'){
char y;
while((y = pop(s)) != '('){
postfix += y;
}
}
else {
while(!IsEmpty(s) && Rank(getTop(s)) >= Rank(x)){
postfix += pop(s);
}
push(s,x);
}
}
char y;
while((y = pop(s)) != NULL){
postfix += y;
}
return postfix;
}
//Tinh bieu thuc
float compute(float a, float b, char o){
if (o == '+') return a + b;
else if (o == '-') return b - a;
else if (o == '*') return a * b;
else if (o == '/') return b / a;
return 0;
}
float Operation(string postfix){
STACK<float> s;
float kq = 0;
int n = postfix.length();
for(int i=0;i<n;i++)
{
char ch = postfix[i];
if(!isOperator(ch))
push(s,float(ch));
else if(isOperator(ch)){
float digit1 = pop(s);
float digit2 = pop(s);
kq = compute(digit1, digit2, ch);
push(s,kq);
}
}
return pop(s);
}
void main()
{
string s1 = "((4+5)*(2+3)+6)/(8+7)";
string postfix = infix2postfix(s1);
cout << "Infix ---> Postfix: " << postfix << endl;
float kq = Operation(postfix);
cout << "Result: " << kq << endl;
cin.get();
}
View more random threads:
xã hội vững mạnh, nhu cầu mặc đẹp của con người ngày càng cao. ngành công nghiệp thời trang cũng đang vững mạnh chóng vánh. những nhà máy gia công hàng may mặc chẳng thể đóng góp lặng thầm vào sự...
Tìm xưởng may gia công tại TP Hồ...