C语言实现表达式求值
用C语言实现表达式求值算法。要求从键盘输入任意的包含加减乘除的算术四则运算表达式,都能求值。操作数类型可以设定为double。
数组栈进行操作
加减乘除和括号运算
以下是代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 50
double stacks[MAX_SIZE];
char stacky[MAX_SIZE];
int tops = 0, bases = 0, topy = 0, basey = 0;
//操作数的操作
void initials();
void pushs(double x);
void pops();
double tops_data();
//操作符的操作
void initialy();
void pushy(char x);
void popy();
char topy_data();
//运算操作
int judge_optr(char top);
double yun(double b, double a, char top);
void operate(char str[]);
void initials() //初始化
{
tops = bases = 0;
}
void pushs(double x) //进栈
{
tops++;
stacks[tops] = x;
}
void pops() //出栈
{
tops--;
}
double tops_data() //栈顶元素
{
return stacks[tops];
}
void initialy()
{
topy = basey = 0;
}
void pushy(char x)
{
topy++;
stacky[topy] = x;
}
void popy()
{
topy--;
}
char topy_data()
{
return stacky[topy];
}
int judge_optr(char top) //返回优先级
{
int x;
switch (top)
{
case '(':
x = 0;
break;
case '+':
case '-':
x = 1;
break;
case '*':
case '/':
x = 2;
break;
case ')':
x = 3;
break;
}
return x;
}
double yun(double b, double a, char top) //运算
{
printf("%.2lf %c %.2lf\n", b, top, a);
double c = 0;
switch (top)
{
case '+':
c = b + a;
break;
case '-':
c = b - a;
break;
case '*':
c = b * a;
break;
case '/':
if (a == 0)
{
printf("ERROR!\n");
return 0;
}
else
c = b / a;
break;
default:
printf("ERROR\n");
break;
}
return c;
}
void operate(char str[])
{
int j;
double a, b, c, f;
char top;
char d[100]; //储存字符串中连续的‘数’或小数
for (int i = 0; str[i] != '\0'; i++)
{
switch (str[i])
{
case '(':
case '+':
case '-':
if ((topy_data() == '#') || ((judge_optr(str[i])) > judge_optr(topy_data())) || (str[i] == '('))
pushy(str[i]); //当操作符栈为空或者该操作符的优先级大于栈顶元素的优先级是入栈保存
else
{
a = tops_data();
pops();
b = tops_data();
pops();
top = topy_data();
pops();
c = yun(b, a, top);
pushs(c); //将计算后的值压入操作数栈中
popy(); //更新操作符栈中的操作符
pushy(str[i]);
}
break;
case '*':
case '/':
if ((topy_data() == '#') || ((judge_optr(str[i])) > judge_optr(topy_data())) || (str[i] == '('))
pushy(str[i]); //当操作符栈为空或者该操作符的优先级大于栈顶元素的优先级是入栈保存
else
{
a = tops_data();
pops();
b = tops_data();
pops();
top = topy_data();
pops();
c = yun(b, a, top);
pushs(c); //将计算后的值压入操作数栈中
popy(); //更新操作符栈中的操作符
pushy(str[i]);
}
break;
case ')':
pushy(str[i]);
break;
default: //处理小数和多个数字字符
j = 0;
do
{
d[j++] = str[i];
i++;
} while (str[i] >= '0' && str[i] <= '9' || str[i] == '.'); //可存入一个或多个数字字符
d[j] = '\0'; //将输入的连续多个数字字符拼成了字符串
i--;
f = atof(d); //调用库函数atoi()将字符数转换为浮点数
pushs(f); //将转换后的数压入操作数栈中
break;
}
}
while (topy_data() != '#')
{
if ((topy_data() == ')') || (topy_data() == '('))
{
popy();
}
else
{
a = tops_data(); //接收从操作数栈中出栈的元素
pops();
b = tops_data(); //接收从操作数栈中出栈的元素
pops();
top = topy_data(); //接收从操作符栈中出栈的元素
popy();
c = yun(b, a, top);
pushs(c); //将计算后的值压入操作数栈中
}
}
}
int main()
{
initials(); //初始化两个栈
initialy();
pushy('#'); //将操作符栈的第一个元素置为'#'
char a[100];
gets(a);
operate(a);
printf("%.2lf", tops_data());
return 0;
}