Sequence_postfix expression(后缀表达式求值)

#include<stdio.h>
#define MAXSIZE 100


double readnumber(char f[], int *i)//将char类型存储的数字转化为double型
{
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;//用k记录小数点后的位数
}
}
while (k != 0)
{
x = x / 10.0;
k = k - 1;
}
//printf("读出的数为:%lf\n", x);
return x;
}


double evalpost(char f[])//求后缀表达式的值
{
double obst[MAXSIZE];//操作数栈,依次存放操作数
int top = 0;
int i = 0;
double x1, x2;
while (f[i] != '#')//结束标志为'#'
{
if (f[i] >= '0'&&f[i] <= '9')
{
obst[top] = readnumber(f, &i);
//printf("top=%lf,", obst[top]);
top++;
}
else 
if (f[i] == ' ')
i++;
else
if (f[i] == '+')
{
x2 = obst[--top];
x1 = obst[--top];
// printf("x1=%lf,x2=%lf", x1, x2);
obst[top] = x1 + x2;
//printf("top=%lf,", obst[top]);
++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[--top];
}


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[])//中缀表达式转后缀表达式
{
int i = 0,j = 0;
char opst[100];
int top, t;
top = 0;
opst[top] = '#';
top++;
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] == ')')//右括号一律出,直到出栈到左括号
{
while (opst[top-1] != '(')
f[j++] = opst[--top];
--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];
f[j] = '\0';//不加'\0',计算结果不正确
}


void main()
{
char c[MAXSIZE];
char f[MAXSIZE];
char ch;
int i = 0;
while (1)
{
ch = getchar();
if (ch == '#')
{
c[i] = ch;
++i;
break;
}
else {
c[i] = ch;
++i;
}
}
c[i] = '\0';
int j = 0;
printf("输入的内容是:");
for (; c[j] != '\0'; ++j)
printf("%c", c[j]);
printf("\n");
postfix(c, f);
int k = 0;
printf("后缀表达式为:");
for (; f[k] != '\0'; ++k)
printf("%c", f[k]);
putchar('\n');
printf("计算结果为:%lf\n", evalpost(f));
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值