编写c程序对用户输入的算式进行对错判断
时间: 2023-08-13 10:08:27 浏览: 60
可以使用栈来实现算式的判断。具体步骤如下:
1. 定义一个字符栈,用于存储左括号和运算符。
2. 遍历输入的算式,对于每个字符进行以下操作:
- 如果是左括号或运算符,则将其压入栈中。
- 如果是右括号,则从栈中弹出一个字符,如果它是对应的左括号,则继续遍历;否则说明括号不匹配,返回错误。
3. 遍历完整个算式后,如果栈为空,则表示算式合法;否则说明还有括号未匹配,返回错误。
下面是一个示例代码:
```c
#include <stdio.h>
#define MAX_STACK_SIZE 100
// 定义字符栈
char stack[MAX_STACK_SIZE];
int top = -1;
// 压栈操作
void push(char ch) {
if (top == MAX_STACK_SIZE - 1) {
printf("Stack overflow!\n");
return;
}
stack[++top] = ch;
}
// 出栈操作
char pop() {
if (top == -1) {
printf("Stack underflow!\n");
return '\0';
}
return stack[top--];
}
// 判断是否为左括号
int is_left_parenthesis(char ch) {
return ch == '(';
}
// 判断是否为右括号
int is_right_parenthesis(char ch) {
return ch == ')';
}
// 判断是否为运算符
int is_operator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
// 判断两个括号是否匹配
int is_match(char ch1, char ch2) {
return (ch1 == '(' && ch2 == ')');
}
// 判断算式是否合法
int is_valid_expression(char* expression) {
for (int i = 0; expression[i] != '\0'; i++) {
if (is_left_parenthesis(expression[i]) || is_operator(expression[i])) {
push(expression[i]);
} else if (is_right_parenthesis(expression[i])) {
char ch = pop();
if (!is_match(ch, expression[i])) {
return 0;
}
}
}
if (top == -1) {
return 1;
} else {
return 0;
}
}
int main() {
char expression[MAX_STACK_SIZE];
printf("Please input an expression: ");
scanf("%s", expression);
if (is_valid_expression(expression)) {
printf("The expression is valid.\n");
} else {
printf("The expression is invalid.\n");
}
return 0;
}
```
这个程序可以判断输入的算式中左右括号是否匹配,但是没有对运算符的顺序进行判断。如果需要判断运算符的顺序,可以使用逆波兰表达式。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)