#刚开始学数据结构,我希望能计算实数范围内的表达式求值,结果出现这样报错,但能计算出正确结果
‘#pragma once
#define ERROR 0
#define OK 1
#define EMPTY 0
template<class T>
struct Node {
T data;
Node<T>* next;
};
template<class T>
class Stack {
Node<T>* top;
public:
Stack();
virtual ~Stack();
int Push(T e);
int Pop(T& e);
int GetTop(T& e);
int IsEmpty();
};
char Precede(char a, char b);
double Operator(double a, char c, double b);
double EvalExpr(char* exp);’
'#include"Expr.h"
#include<iostream>
#include<cmath>
using namespace std;
template<class T>
Stack<T>::Stack() {
top = new Node<T>;
top->next = NULL;
}
template<class T>
Stack<T>::~Stack() {
Node<T>* p;
while (top) {
p = top;
top = top->next;
delete p;
}
}
template<class T>
int Stack<T>::Push(T e) {
Node<T>* p = new Node<T>;
if (!p) return ERROR;
p->data = e;
p->next = top->next;
top->next = p;
return OK;
}
template<class T>
int Stack<T>::Pop(T& e) {
Node<T>* p;
if (top->next == NULL)
return ERROR;
p = top->next;
e = p->data;
top->next = p->next;
delete p;
return OK;
}
template<class T>
int Stack<T>::GetTop(T& e) {
if (top->next == NULL)
return ERROR;
e = top->next->data;
return OK;
}
template<class T>
int Stack<T>::IsEmpty() {
if (top)
return OK;
return EMPTY;
}
char Precede(char a, char b) {
char PriorTable[7][7] = {
{'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=',' '},
{'>','>','>','>','>','>','>'},
{'<','<','<','<','<',' ','='}
};
int x = -1, y = -1;
char opr[] = "+-*/()=";
for (int i = 0; i < 7; i++) {
if (a == opr[i]) x = i;
if (b == opr[i]) y = i;
}
return PriorTable[x][y];
}
double Operator(double a, char c, double b) {
switch (c) {
case'+':return a + b;
case'-':return a - b;
case'*':return a * b;
case'/':return a / b;
default:return ERROR;
}
}
double EvalExpr(char* exp) {
Stack<char>OPTR;
OPTR.Push('=');
Stack<double>OPND;
char op, c, theta, x;
double a, b;
double n = 0,f=0;
int i,temp=0,j=1,k=0;
c = *exp++;
OPTR.GetTop(op);
while (c != '=' || op != '=') {
cout << exp <<' '<<c << endl;
if (c >= '0' && c <= '9') {
k = 1;
if (temp == 0) {
n = n * 10 + c - '0';
c = *exp++;
}
else {
i=c - '0';
f = i;
n= n+f * pow(10, -temp);
temp++;
c = *exp++;
}
}
else if (k == 0 && c == '-') {
j = -j;
c = *exp++;
}
else if (c == '.') {
temp =1;
c = *exp++;
}
else {
if (n != 0) {
n = n * j;
cout << n << endl;
OPND.Push(n);
n = 0;
f = 0;
temp = 0;
j = 1;
k = 1;
}
switch (Precede(op, c)) {
case'<':
OPTR.Push(c);
k = 0;
c = *exp++;
break;
case'=':
OPTR.Pop(x);
c = *exp++;
break;
case'>':
OPTR.Pop(theta);
OPND.Pop(b);
OPND.Pop(a);
cout << a << theta << b << endl;
OPND.Push(Operator(a, theta, b));
break;
}
}
OPTR.GetTop(op);
}
OPND.GetTop(a);
return a;
}'
'
#include<iostream>
using namespace std;
#include"Expr.h"
int main() {
char* ptr = new char;
cout << "请输入要求值的表达式" << endl;
cin >> ptr;
cout << EvalExpr(ptr);
return 0;
}'
顶