用C语言编写一个可以无限加减乘除可以带括号的简单计算器程序
时间: 2023-04-05 17:01:21 浏览: 126
利用C语言编写的一个计算器
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是一个简单的可以无限加减乘除可以带括号的计算器程序的 C 语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_EXPRESSION_LENGTH 100
int evaluate_expression(char* expression);
int main() {
char expression[MAX_EXPRESSION_LENGTH];
printf("请输入一个数学表达式:");
fgets(expression, MAX_EXPRESSION_LENGTH, stdin);
int result = evaluate_expression(expression);
printf("结果为:%d\n", result);
return 0;
}
int evaluate_expression(char* expression) {
int result = 0;
int current_number = 0;
char current_operator = '+';
int i = 0;
while (expression[i] != '\0') {
if (expression[i] >= '0' && expression[i] <= '9') {
current_number = current_number * 10 + (expression[i] - '0');
} else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') {
if (current_operator == '+') {
result += current_number;
} else if (current_operator == '-') {
result -= current_number;
} else if (current_operator == '*') {
result *= current_number;
} else if (current_operator == '/') {
result /= current_number;
}
current_number = 0;
current_operator = expression[i];
} else if (expression[i] == '(') {
int j = i + 1;
int parentheses_count = 1;
while (parentheses_count > 0) {
if (expression[j] == '(') {
parentheses_count++;
} else if (expression[j] == ')') {
parentheses_count--;
}
j++;
}
char sub_expression[MAX_EXPRESSION_LENGTH];
strncpy(sub_expression, expression + i + 1, j - i - 2);
sub_expression[j - i - 2] = '\0';
int sub_result = evaluate_expression(sub_expression);
if (current_operator == '+') {
result += sub_result;
} else if (current_operator == '-') {
result -= sub_result;
} else if (current_operator == '*') {
result *= sub_result;
} else if (current_operator == '/') {
result /= sub_result;
}
current_number = 0;
i = j - 1;
}
i++;
}
if (current_operator == '+') {
result += current_number;
} else if (current_operator == '-') {
result -= current_number;
} else if (current_operator == '*') {
result *= current_number;
} else if (current_operator == '/') {
result /= current_number;
}
return result;
}
```
这个程序可以读入一个数学表达式,然后计算出它的结果。它支持无限加减乘除和带括号的表达式。例如,输入 "(1+2)*3",输出 "9"。
阅读全文