目录
对于一个不存在括号的表达式进行计算
存在多组数据,每组数据一行,表达式不存在空格
输出结果
输入:
6/2+3+3*4输出:
18
AC代码~
#include<stdio.h>
#include<string.h>
int IsOper(char ch) {
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
return 1;
else
return 0;
}
int main() {
double S_num[100];
int top2 = -1;
char s[100];
while (gets(s)) {
int len = strlen(s);
int i = 0;
top2 = -1;
char lastOper = '#';
while (i < len) {
if (i == 0) { // 处理第一个数
int t = s[i] - '0';
i++;
while ('0' <= s[i] && s[i] <= '9') {
t = t * 10 + (s[i] - '0');
i++;
}
top2++;
double x = t;
S_num[top2] = x;
}
if (IsOper(s[i])) {
lastOper = s[i];
i++;
} else {
int t = s[i] - '0';
i++;
while ('0' <= s[i] && s[i] <= '9') {
t = t * 10 + (s[i] - '0');
i++;
}
double x = t;
if (lastOper == '+' ) {
top2++;
S_num[top2] = x;
} else if (lastOper == '-') {
top2++;
S_num[top2] = -x;
} else if (lastOper == '*') {
double numtop = S_num[top2];
S_num[top2] = x * numtop;
} else {
double numtop = S_num[top2];
S_num[top2] = numtop * 1.0 / x;
}
}
}
double sum = 0;
for (int i = 0; i <= top2; i++)
sum += S_num[i];
int x2 = sum;
printf("%d\n", x2);
}
return 0;
}