“ Ctrl AC!一起 AC!”
前缀表达式求值:
#include<bits/stdc++.h>
using namespace std;
char s[100];
double scan(){
cin>>s;
if(s[0]>='0'&&s[0]<='9'){
return atof(s);
}
else{
if(s[0]=='+') return scan()+scan();
else if(s[0]=='-') return scan()-scan();
else if(s[0]=='*') return scan()*scan();
else return scan()/scan();
}
}
int main(){
printf("%f",scan());
return 0;
}
中缀转后缀:
int is_operation(char op){
switch(op){
case '+':
case '-':
case '*':
case '/': return 1;
default: return 0;
}
}
int priority(char op){
switch(op){
case '#': return -1;
case '(': return 0;
case '+':
case '-': return 1;
case '*':
case '/': return 2;
default : return -1;
}
}
void postfix(char e[],char f[]){ //将中缀表达式e转换成后缀表达式f
char opst[100];int top=0;
opst[top]='#';top++;
int i=0,j=0;
while(e[i]!='#'){
if((e[i]>='0'&&e[i]<='9')||e[i]=='.') f[j++]=e[i];
else if(e[i]=='('){
opst[top]=e[i];top++;
}
else if(e[i]==')'){
t=top-1;
while(opst[t]!='(') {
f[j++]=opst[--top];t=top-1;
}
top--;
}
else if(is_operation(e[i])){
f[j++]=' '; //用空格分开两个操作数
while(priority(opst[top-1])>=priority(e[i])) f[j++]=opst[--top];
opst[top]=e[i];top++;
}
++i;
}
while(top) f[j++]=opst[--top];
}
后缀表达式求值:
double readnumber(char f[],int *i){ //将字符字符串转变成数
double x=0.0;
int k=0;
while(f[*i]>='0'&&f[*i]<='9'){
x=x*10+(f[*i]-'0');
(*i)++;
}
if(f[*i]=='.'){
(*i)++;
while(f[*i]>='0'&&f[*i]<='9'){
x=x*10+(f[*i]-'0');
(*i)++;
k++; //记录小数点后面有几位
}
}
while(k!=0){
x=x/10.0;
k--;
}
return x;
}
double evalpost(char f[]){
double obst[100]; //实时操作数操作记录
int top=0;
int i=0;
double x1,x2;
while(f[i]!='#'){
if(f[i]>='0'&&f[i]<='9'){
obst[top]=readnumber(f,&i);
top++;
}
else if(f[i]==' ') i++;
else if(f[i]=='+'){
x2=obst[--top];
x1=obst[--top];
obst[top]=x1+x2;
top++;
i++;
}
else if(f[i]=='-'){
x2=obst[--top];
x1=obst[--top];
obst[top]=x1-x2;
top++;
i++;
}
else if(f[i]=='*'){
x2=obst[--top];
x1=obst[--top];
obst[top]=x1*x2;
top++;
i++;
}
else if(f[i]=='/'){
x2=obst[--top];
x1=obst[--top];
obst[top]=x1/x2;
top++;
i++;
}
}
return obst[0];
}
感谢阅读!!!
“ Ctrl AC!一起 AC!”