版权声明: https://blog.csdn.net/jtjljy/article/details/82880554
自己练练手,写了个栈用来进行表达式求值。
记录一下~(用‘#’表示开始结束~)
不过可能也存在着一些问题,就是用double存整数可能会出现问题,另外异常处理还没有完善。
还存在很大优化空间。
#include <iostream>
#include <sys/malloc.h>
//win上为malloc.h
#include <cmath>
using namespace std;
typedef int Status;
#define OK 0
#define ERROR -1
#define ET double
struct node{
//int stacksize;
ET data;
node * next;
};
struct stack{
node * base;
node * top;
};
typedef node* Node;
typedef stack* Stack;
Stack init(){
Stack head=(Stack) malloc(sizeof(stack));
Node n= (Node)malloc(sizeof(node));
head->base=n;
head->top=head->base;
return head;
}
Status Insert(Stack head,ET x)
{
head->top->data=x;
if(head->top==head->base)
{
head->top->next=NULL;
}
Node n=(Node)malloc(sizeof(node));
n->next=head->top;
head->top=n;
return OK;
}
ET Pop_Node(Stack head)
{
if(head->top==NULL)
return ERROR;
ET tmp=head->top->next->data;
head->top=head->top->next;
return tmp;
}
int rules[7][7]={
1,1,0,0,0,1,1,
1,1,0,0,0,1,1,
1,1,1,1,0,1,1,
1,1,1,1,0,1,1,
0,0,0,0,0,-1,-2,
1,1,1,1,-2,1,1,
0,0,0,0,0,-2,-1
};//-1相等,0小于,1大于,-2无
/*
* 0 +
* 1 -
* 2 *
* 3 /
* 4 (
* 5 )
* 6 #
*/
int char_to_int(ET c)
{
switch (int(c)){
case '+':
return 0;
case '-':
return 1;
case '*':
return 2;
case '/':
return 3;
case '(':
return 4;
case ')':
return 5;
case '#':
return 6;
default:
return -1;
}
}
Status Check(ET c1,ET c2)
{
int c_1=char_to_int(c1);
int c_2=char_to_int(c2);
return rules[c_1][c_2];
}
int main() {
Stack head_num = init();
Stack head_char = init();
Insert(head_char,'#');
char c[1000];
//char tmp_c[10];
cout<<"===表达式求值-1.0 CS1702 Kingtous==="<<endl;
cout<<"请输入你要计算的表达式:";
cin.getline(c, sizeof(c));
int pos=0;
for (;c[pos]!='\0';++pos);
c[pos]='#';
//cin.getline(tmp_c, sizeof(tmp_c));
for (int i=0;c[i]!='\0';++i)
{
int p=-1;
bool isPoint=false;
if(c[i]<='9' && c[i]>='0')
{
double total=c[i]-'0';
while((c[i+1]>='0' && c[i+1]<='9')|| c[i+1]=='.')
{
if(c[i+1]=='.')
{
isPoint= true;
i++;
}
i++;
if(isPoint)
{
total=total+(c[i]-'0')*pow(10,p);
p--;
}
else
total=total*10+(c[i]-'0');
}
Insert(head_num,total);
}
else
{
isPoint=true;//reset
p=-1;//reset
//-1相等,0小于,1大于,-2无
check_again:
switch ( Check(head_char->top->next->data,c[i]) )
{
case 0:
Insert(head_char,c[i]);
break;
case -1:
Pop_Node(head_char);
break;
case 1:
double num1=Pop_Node(head_num);
double num2=Pop_Node(head_num);
char ch= int(Pop_Node(head_char));
switch (ch)
{
case '+':
Insert(head_num,num2+num1);
break;
case '-':
Insert(head_num,num2-num1);
break;
case '*':
Insert(head_num,num2*num1);
break;
case '/':
Insert(head_num,num2/num1);
break;
}
goto check_again;
}
}
}
cout<<"表达式 = "<<Pop_Node(head_num)<<endl;
return 0;
}