给大家搞了一个C语言用栈实现表达式计算
- 可以支持±*/()
- 可以进行小数,整数运算,但是吧,精度这个问题我就没解决
- 建立了两个栈,一个存储运算符,一个存储数字
- (是存在运算符栈的
- 遇到)就要pop栈直到把遇到的第一个(也给pop掉
- 是按照运算优先级进行操作的
- 例如3*5+ 新的即将要插入的+没有*优先级高,那就先搞出数字栈的最上面两个数字,和运算符栈搞出*然后做运算得到15,把15再放入数字栈栈顶,然后把+放入运算符栈。
- 代码直接可以用,输入3*5+2=,结尾一定要是等号!!!!!!!
- 记得点赞
上代码
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#pragma warning(disable:4996)
#define maxsize 100
typedef struct SqList_char{
int top;
int bottom;
char data[maxsize];
}Sqlist_char;
typedef struct SqList_float {
int top;
int bottom;
float data[maxsize];
}Sqlist_float;
void initStack_char(Sqlist_char *L){
L->top = 0;
L->bottom = 0;
}
void initStack_float(Sqlist_float* L) {
L->top = 0;
L->bottom = 0;
}
char popStack_char(SqList_char* p) {
char str;
if (p->top != p->bottom) {
str = p->data[p->top - 1];
p->top--;
return str;
}
}
float popStack_float(SqList_float* p) {
float f1;
if (p->top != p->bottom) {
f1= p->data[--p->top];
return f1;
}
}
int pushStack_char(SqList_char* p, char str) {
if (p->top >= maxsize) {
return 1;
}
else
{
p->data[p->top++] = str;
return 1;
}
}
int pushStack_float(SqList_float* p, float str) {
if (p->top >= maxsize) {
return 0;
}
else
{
p->data[p->top++] = str;
return 1;
}
}
int compare(char a,char b)