C语言题目 表达式计算
发布网友
发布时间:2023-02-14 11:30
我来回答
共1个回答
热心网友
时间:2023-09-12 13:57
假设没有括号匹配错误, 支持多余空白, 支持负数
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
char str[110];
double seq[110];
int is_op[110];
int stk[110];
int level(int v) {
switch(v) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
return -1;
}
int main() {
int len;
double pre_num = 0, num = 0, sign = 1;
int sql = 0, stk_top = 0;
int i;
scanf("%s", str);
len = strlen(str);
seq[sql] = '(';
is_op[sql++] = 1;
for (i = 0; i < len; ++i) {
if (isspace(str[i])) {
continue;
} else if (isdigit(str[i])) {
num *= 10;
num += str[i] - '0';
pre_num = 1;
} else {
if (pre_num) {
pre_num = 0;
seq[sql++] = num * sign;
sign = 1;
num = 0;
} else if (str[i] == '-') {
sign = -1;
continue;
}
seq[sql] = str[i];
is_op[sql++] = 1;
}
}
if (pre_num) {
seq[sql++] = num * sign;
}
seq[sql] = ')';
is_op[sql++] = 1;
for (i = 0; i < sql; ++i) {
if (seq[i] == '(') {
stk[stk_top++] = i;
} else if (seq[i] == ')') {
int lr = stk[--stk_top];
int j;
int pre_op = '+';
double pre1_num = 0, pre2_num = seq[lr + 1], ans;
for (j = lr + 2; j < i; ++j) {
if (level(seq[j]) > 1) {
if (seq[j] == '*') {
pre2_num *= seq[++j];
} else {
pre2_num /= seq[++j];
}
} else {
if (pre_op == '+') {
pre1_num += pre2_num;
} else {
pre1_num -= pre2_num;
}
pre_op = seq[j];
pre2_num = seq[++j];
}
}
if (pre_op == '+') {
ans = pre1_num + pre2_num;
} else {
ans = pre1_num - pre2_num;
}
seq[lr++] = ans;
memmove(seq + lr, seq + i + 1, (sql - i) * sizeof(double));
memmove(is_op + lr, is_op + i + 1, (sql - i) * sizeof(int));
sql -= i - lr + 1;
i = lr;
}
}
printf("%.3lf", seq[0]);
}