#include <stdio.h> #include <stdbool.h>

bool checkParentheses(char* expression) { int count = 0; for (int i = 0; expression[i] != '\0'; i++) { if (expression[i] == '(') { count++; } else if (expression[i] == ')') { count--; if (count < 0) { return false; } } } return count == 0; }

int main() { char expression1[] = "(1+3*(2+4)+5)+6"; char expression2[] = "1+3*(2+4)+5)+6";

if (checkParentheses(expression1)) {
    printf("括号是匹配的\n");
} else {
    printf("括号是不匹配的\n");
}

if (checkParentheses(expression2)) {
    printf("括号是匹配的\n");
} else {
    printf("括号是不匹配的\n");
}

return 0;

}

该函数使用一个整型变量count来记录遇到的左括号的数量。遍历表达式中的每个字符,如果遇到左括号,则count加1;如果遇到右括号,则count减1。如果count小于0,说明出现了未匹配的右括号,返回false。最后,如果count等于0,说明括号是匹配的,返回true;否则括号是不匹配的,返回false

C语言判断数学表达式中括号是否匹配的函数

原文地址: https://www.cveoy.top/t/topic/p5ar 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录