c语言编写计算器四则运算小数和括号
时间: 2023-09-13 22:14:02 浏览: 198
以下是一个简单的计算器程序,可以支持四则运算、小数和括号:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_EXPR_LEN 100 // 表达式最大长度
// 运算符栈
char opstack[MAX_EXPR_LEN];
int op_top = -1;
// 数字栈
double numstack[MAX_EXPR_LEN];
int num_top = -1;
// 运算符优先级
int priority(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
return 0;
}
return -1;
}
// 计算表达式
double evaluate(char *expr) {
op_top = -1;
num_top = -1;
char *p = expr;
while (*p != '\0') {
if (isdigit(*p) || *p == '.') {
// 数字入栈
double num = strtod(p, &p);
numstack[++num_top] = num;
} else if (*p == '(') {
// 左括号入栈
opstack[++op_top] = '(';
p++;
} else if (*p == ')') {
// 右括号计算
while (op_top >= 0 && opstack[op_top] != '(') {
char op = opstack[op_top--];
double b = numstack[num_top--];
double a = numstack[num_top--];
switch (op) {
case '+':
numstack[++num_top] = a + b;
break;
case '-':
numstack[++num_top] = a - b;
break;
case '*':
numstack[++num_top] = a * b;
break;
case '/':
numstack[++num_top] = a / b;
break;
}
}
if (op_top >= 0 && opstack[op_top] == '(') {
op_top--;
}
p++;
} else {
// 运算符计算
while (op_top >= 0 && priority(opstack[op_top]) >= priority(*p)) {
char op = opstack[op_top--];
double b = numstack[num_top--];
double a = numstack[num_top--];
switch (op) {
case '+':
numstack[++num_top] = a + b;
break;
case '-':
numstack[++num_top] = a - b;
break;
case '*':
numstack[++num_top] = a * b;
break;
case '/':
numstack[++num_top] = a / b;
break;
}
}
opstack[++op_top] = *p++;
}
}
while (op_top >= 0) {
char op = opstack[op_top--];
double b = numstack[num_top--];
double a = numstack[num_top--];
switch (op) {
case '+':
numstack[++num_top] = a + b;
break;
case '-':
numstack[++num_top] = a - b;
break;
case '*':
numstack[++num_top] = a * b;
break;
case '/':
numstack[++num_top] = a / b;
break;
}
}
return numstack[num_top];
}
int main() {
char expr[MAX_EXPR_LEN];
printf("请输入表达式:");
scanf("%s", expr);
double result = evaluate(expr);
printf("%s = %f\n", expr, result);
return 0;
}
```
运行示例:
```
请输入表达式:(1.2+2.3)*3.4-4.5/5.6
(1.2+2.3)*3.4-4.5/5.6 = 8.139286
```
阅读全文