用C++帮我设计一个程序,能够判断一个运算的表 达式形式上是否正确
时间: 2023-06-11 16:08:32 浏览: 35
好的,以下是一个简单的程序,可以判断一个运算的表达式形式上是否正确:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_EXPR_LENGTH 100
int is_operator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int is_operand(char c) {
return (isdigit(c) || isalpha(c));
}
int is_valid_expression(char *expr) {
int len = strlen(expr);
int i, j, k;
// Check for empty expression
if (len == 0) {
return 0;
}
// Check for invalid characters
for (i = 0; i < len; i++) {
if (!isdigit(expr[i]) && !isalpha(expr[i]) && !is_operator(expr[i])) {
return 0;
}
}
// Check for invalid operators
if (is_operator(expr[0]) || is_operator(expr[len-1])) {
return 0;
}
for (i = 1; i < len-1; i++) {
if (is_operator(expr[i]) && is_operator(expr[i+1])) {
return 0;
}
}
// Check for balanced parentheses
int count = 0;
for (i = 0; i < len; i++) {
if (expr[i] == '(') {
count++;
} else if (expr[i] == ')') {
count--;
}
if (count < 0) {
return 0;
}
}
if (count != 0) {
return 0;
}
// Check for consecutive operands
for (i = 0; i < len-1; i++) {
if (is_operand(expr[i]) && is_operand(expr[i+1])) {
return 0;
}
}
// Check for consecutive operators
for (i = 0; i < len-1; i++) {
if (is_operator(expr[i]) && is_operator(expr[i+1])) {
return 0;
}
}
// Check for invalid operands
for (i = 0; i < len; i++) {
if (isalpha(expr[i])) {
for (j = i+1; j < len; j++) {
if (is_operator(expr[j])) {
break;
}
}
char *operand = (char*) malloc(sizeof(char) * (j-i));
strncpy(operand, expr+i, j-i);
operand[j-i] = '\0';
for (k = 0; k < strlen(operand); k++) {
if (!isalpha(operand[k])) {
free(operand);
return 0;
}
}
free(operand);
i = j-1;
}
}
return 1;
}
int main() {
char expr[MAX_EXPR_LENGTH];
printf("Enter an expression: ");
fgets(expr, MAX_EXPR_LENGTH, stdin);
if (is_valid_expression(expr)) {
printf("The expression is valid.\n");
} else {
printf("The expression is invalid.\n");
}
return 0;
}
```
该程序通过检查表达式中字符的类型、括号是否平衡、是否存在连续的操作数或操作符、以及是否有无效操作数等多个方面来判断表达式形式是否正确。