算术表达式求值
问题描述:编写程序,计算算术表达式串的值,具体要求如下:
①表达式串在运行时输入。
②表达式串支持+、-、、/(精确除)
、%(整除取余)
、圆括号等运算符,且支持任意位数的整
形常量和浮点型常量。如“33/2-(41.23+2)(52%7)”的值为“-113.19”
。
③运算符优先级依次为:括号、乘除、加减,若优先级相同,则从左至右。
④当表达式串非法时,能提示信息。
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef struct SqNode{
char data;
struct SqNode *next;
}SqNode,*SqStack;
int InitStack(SqStack &S) {
S=NULL;
return OK;
}
int Push(SqStack &S, char e) {//入栈
SqNode *p =(SqStack)malloc(sizeof(SqNode));
if (!p) {
return OVERFLOW;//溢出
}
p->data=e;
p->next=S;
S=p;
return OK;
}
int Pop(SqStack &S,char &e) {//出栈
SqNode p;
if (!S)
return ERROR;//空栈
e=S->data;
p=S;
S=S->next;
free(p);
return OK;
}
int GetTop(SqStack &S) {//获得栈顶元素值
if (!S)
return ERROR;//空栈
return S->data;
}
int In(char ch) {//判断ch是否为运算符
if(ch=='+'||ch=='-'||ch=='#'||ch==''||ch=='/'||ch=='('||ch==')')
return 1;
else return 0;
}
int Out(char ch){//判断ch是否为数字
if(ch=='1'||ch=='2'||ch=='3'||ch=='4'||ch=='5'||ch=='6'||ch=='7'||ch=='8'||ch=='9'||ch=='0')
return 1;
else return 0;
}
char Precede(char theta1, char theta2) {//判断运算符优先级
if ((theta1=='('&&theta2==')')||(theta1=='#'&&theta2=='#')){
return '=';
} else if (theta1=='('||theta1=='#'||theta2=='('||(theta1=='+'||theta1=='-')&&(theta2==''||theta2=='/')){
return '<';
} else
return '>';
}
char Operate(char first, char theta, char second) {//计算两数运算结果
switch (theta) {
case '+':
return (first-'0'/得到数字/)+(second-'0')+48;//得到char
case '-':
return (first-'0')-(second-'0')+48;
case '':
return (first-'0')*(second-'0')+48;
case '/':
return (first-'0')/(second-'0')+48;
}
return 0;
}
//表达式求值
char EvaluateExpression() {
SqStack OPTR,OPND;
char ch,theta,a,b,x,top;
InitStack(OPND);
InitStack(OPTR);
Push(OPTR,'#');
scanf("%c",&ch);
while(ch!='#'||(GetTop(OPTR)!='#'))
{
if(Out(ch))//如果是数字
{ Push(OPND,ch);
scanf("%c",&ch);
}
else if(In(ch))//如果是运算符
switch (Precede(GetTop(OPTR),ch))
{
case '<':
Push(OPTR,ch);//入栈
scanf("%c",&ch);
break;
case '=':
Pop(OPTR,x);//出栈
scanf("%c",&ch);
break;
case '>':
Pop(OPTR,theta);
Pop(OPND,b);
Pop(OPND,a);
Push(OPND,Operate(a,theta,b));
break;
}
else {
printf("输入错误,请重新输入!\n");
ch='0';
continue;
}
}
return GetTop(OPND); //OPND栈顶元素即为表达式求值结果
}
int menu() {
int c;
printf("表达式求解程序:\n");
printf("1.开始计算\n");
printf("0.退出程序\n");
printf("请选择:");
scanf("%d",&c);
getchar();
return c;
}
int main() {
while (1) {
switch (menu()) {
case 1: {
printf("请输入表达式(以#结束):\n");
char x = EvaluateExpression();//表达式求值
printf("计算结果为:");
printf("%d\n",x-'0');
printf("******************************************\n\n");
}
break;
case 0:
printf("退出成功\n");
exit(0);
default:
break;
}
}
return 0;
}
将中缀表达式
转换成后缀表达式
再做。
https://www.cnblogs.com/whlook/p/7143327.html