用c语言来写判断算数表达式中开括号和闭括号是否配对
时间: 2024-05-05 10:16:16 浏览: 117
用C语言检查输入括号是否匹配
5星 · 资源好评率100%
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
int main() {
char expression[MAX_SIZE];
int stack[MAX_SIZE], top = -1;
int i, len, flag = 1;
printf("Enter an arithmetic expression: ");
fgets(expression, MAX_SIZE, stdin);
len = strlen(expression);
expression[len - 1] = '\0'; // remove the newline character at the end
for (i = 0; i < len; i++) {
if (expression[i] == '(') {
stack[++top] = i;
} else if (expression[i] == ')') {
if (top == -1) {
flag = 0; // unpaired closing bracket
break;
} else {
top--;
}
}
}
if (top != -1) {
flag = 0; // unpaired opening bracket
}
if (flag) {
printf("The brackets in the expression are paired.\n");
} else {
printf("The brackets in the expression are not paired.\n");
}
return 0;
}
```
注:该代码使用了一个整型数组实现了栈结构,并且只支持单行输入。
阅读全文