# 【C语言】—— 实现简易四则运算

## 实现简易四则运算表达式

#### 全部代码如下：

#include <stdio.h>
#include <string.h>
int Calculation(int a, char c, int b);
void ScanfData();
int Compare(char ch);
int main() {
ScanfData();
return 0;
}

int Calculation(int a, char c, int b) {
if (c == '+') {
return a + b;
} else if (c == '-') {
return a - b;
} else if (c == '*') {
return a * b;
} else if (c == '/') {
return a / b;
} else {
return -1;
}
}
void ScanfData() {
int numStack[100] = {0};
int numTop = -1;
char symStack[100] = {'='};
int symTop = 0;
char str[100];
int flag = -1;
scanf("%s", str);
int x = 0;
int length = (int)strlen(str);
int i = 0;
while (i < length) {
if (str[i] >= '0' && str[i] <= '9') {
x = x * 10 + (str[i++] - '0');
flag = 1;
} else {
if (flag == 1) {
numStack[++numTop] = x;
x = 0;
flag = -1;
}
if (Compare(symStack[symTop]) < Compare(str[i])) {
symStack[++symTop] = str[i++];
} else {
int b = numStack[numTop--];
int a = numStack[numTop--];
numStack[++numTop] = Calculation(a, symStack[symTop], b);
symTop--;
if (str[i] == '=' && symTop == 0) {
break;
}
}
}
}
printf("%d", numStack[numTop]);
}
int Compare(char c) {
if (c == '=') {
return 0;
} else if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
} else {
printf("error");
return -1;
}
}



#### 栈和队列简单练习题：

char* removeDuplicates(char* s) {
int len = strlen(s);
int i, j = 0;
char *q = (char *)malloc(sizeof(char) * len);
for (i = 0; i < len; i++) {
q[j] = s[i];
if (j > 0) {
if (q[j] == q[j - 1]) {
j = j - 2;
}
}
j++;
}
q[j] = '\0';
return q;
}


int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize){
int stu0 = 0, stu1 = 0;
int i;
for (i = 0; i < studentsSize; i++) {
if (students[i] == 0) {
stu0++;
} else {
stu1++;
}
}
for (i = 0; i < sandwichesSize; i++) {
if (sandwiches[i] == 0) {
if (stu0 == 0) {
return studentsSize - i;
} else {
stu0--;
}
} else {
if (stu1 == 0) {
return studentsSize - i;
} else {
stu1--;
}
}
}
return 0;
}


int timeRequiredToBuy(int* tickets, int ticketsSize, int k){
int i = 0, count = 0;
if (tickets[k] == 0) {
return 0;
}
while (i <= k) {
for (int j = 0; j < ticketsSize; j++) {
tickets[j]--;
if (tickets[j] >= 0) {
count++;
}
if (tickets[k] == 0) {
return count;
}
}
}
return 0;
}

• 0
点赞
• 9
收藏
觉得还不错? 一键收藏
• 3
评论
05-05 1万+
12-02 1909
04-16
09-03 4万+
04-16
08-05 316
01-06 5465
05-28
12-30
05-28
12-21

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