中綴運算式求值,中綴求值
中綴運算式用於計算一個運算式,比如計算機 就是這樣實現的
這兒是用棧的資料結構來實現的。首先輸入一個字串,表示一個運算式,然後用一個棧儲存數字,另外一個棧儲存符號
如果當前運算子優先順序比棧頂元素優先順序高,則入棧,若當前運算子優先順序小於等於棧頂運算子優先順序,則從數字棧中彈出兩個元素,從符號棧中彈出一個符號,計算結果入棧(數字棧);
代碼如下:
#include<iostream>
using namespace std;
#include<cstring>
#include<stack>
#include<cmath>
int judge(char x,char popx);
int func(int x,char str,int y);
int main()
{
int w;
cin>>w ;
while(w--)
{
stack<int>a;
stack<char>str;
int i,n;
char s[2000];
str.push('#'); //判斷棧空的條件
cin>>s;
for(i=0;i<strlen(s);)
{
if(s[i]-'0'>=0&&s[i]-'0'<=9)
{
int m[20],j;
for(j=i;s[j]-'0'>=0&&s[j]-'0'<=9;j++) //計算數位時候,因為數字可能大於10,所以這兒要專門計算
m[j-i]=s[j]-'0';
int sum=0;
for(int k=j-i-1;k>=0;k--)
sum+=m[k]*pow(10,j-i-k-1);
a.push(sum);
i=j;
}
else
{
if(judge(str.top(),s[i])==2) //入棧
{
str.push(s[i]);
i++;
}
else
if(judge(str.top(),s[i])==1) //出棧先算
{
int numb1=a.top();
a.pop();
int numb2=a.top();
a.pop();
a.push(func(numb2,str.top(),numb1));
str.pop();
}
else
if(judge(str.top(),s[i]==3)) //括弧
{
str.pop();
i++;
}
}
}
while(true)
{
if(str.top()=='#')
{
cout<<a.top()<<endl;
a.pop();
break;
}
else
{
int numb5=a.top();
a.pop();
int numb6=a.top();
a.pop();
a.push(func(numb6,str.top(),numb5));
str.pop();
}
}
}
}
int judge(char popx,char x) //確定優先順序
{
if(popx=='*'||popx=='/')
{
if(x=='(')
return 2; //直接入棧
else
if(x=='+'||x=='-'||x==')'||x=='*'||x=='/')// 出棧先算
return 1;
}
else
if(popx=='+'||popx=='-')
{
if(x=='*'||x=='/'||x=='(') //直接入棧
return 2;
else
if(x=='+'||x=='-'||x==')')
return 1;
}
else
if((popx=='('&&x!=')')||popx=='#')
return 2; //直接入棧
else
if(popx=='('&&x==')')
return 3;
}
int func(int x,char str,int y) //計算值
{
if(str=='+')
return x+y;
if(str=='-')
return x-y;
if(str=='*')
return x*y;
if(str=='/')
return x/y;
}
完成標準中綴算術運算式值運算
以前寫過這種逆波蘭演算法,不過是用C#寫的。另外當時寫該演算法時沒考慮到指數運算,只考慮到四則運算。需要的話可以發你的E-Mail,可以把C#的源碼發給你參考。代碼很多,這裡貼不出來。
以下是C#版逆波蘭演算法示範:
計算中綴運算式
正好我們有一道上機題是要將中綴變尾碼,再進行運算式求值,我把代碼全弄過來了,程式沒問題,你自己看吧
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
/*棧節點類型*/
typedef struct node
{
char data;
struct node *next;
}snode,*slink;
typedef struct node_post
{
int data;
struct node_post *next;
}pnode,*plink;
/*全域變數定義*/
slink top=NULL;
plink ptop=NULL;
/*棧空檢測,空時為1*/
int Emptystack()
{
if(top==NULL)return 1;
else return 0;
}
/*出棧,返回top中data*/
char Pop()
{
char e;
slink p;
if(top==NULL)return(-1);
else
{
p=top;
top=top->next;
e=p->data;
free(p);
return e;
}
}
int Pop_post()
{
int e;
plink p;
if(ptop==NULL)return(-1);
else
{
p=ptop;
ptop=ptop->next;
e=p->data;
free(p);
return e;
}
}
/*進棧*/
void Push(char e)
{
slink p;
p=(slink)malloc(sizeof(snode));
p->data=e;
p->next=top;
top=p;
}
void Push_post(int e)
{
plink p;
p=(plink)malloc(sizeof(pnode));
p->data=e;
p->next=ptop;
ptop=p;
}
/*取棧頂*/
char Gettop()
{ if(!Emptystack(top))return (top->data);
else return 0;
}
/*符號優先順序比較*/
int Precede(char x,char y)
{
int a,b;
switch(x)
{
case '#':a=-1;break; /*insert this line*/
case '(':a=0;break;
case '+':
case '-':a=1;break;
case '*':
case '/':......餘下全文>>