实现可重复计算的可以计算加减乘除根号指数运算的中缀形式的计算器
时间: 2024-02-16 16:00:35 浏览: 24
好的,以下是一个可以计算加减乘除根号指数运算的中缀表达式计算器,并且支持可重复计算:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_SIZE 100
void clear_input_buffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
double calculate(double num1, double num2, char operator) {
switch (operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 == 0) {
printf("Error: divide by zero\n");
return 0;
} else {
return num1 / num2;
}
case '^':
return pow(num1, num2);
case 'r':
return pow(num2, 1.0/num1);
default:
printf("Invalid operator\n");
return 0;
}
}
int main() {
double stack[MAX_SIZE];
char operator_stack[MAX_SIZE];
int top = -1, operator_top = -1;
double num, result;
char operator, input[MAX_SIZE];
while (1) {
printf("Enter an expression (or 'q' to quit): ");
fgets(input, MAX_SIZE, stdin);
if (input[0] == 'q') {
break;
}
char *token = strtok(input, " ");
while (token) {
if (sscanf(token, "%lf", &num) == 1) {
stack[++top] = num;
} else {
operator = token[0];
if (operator == '(') {
operator_stack[++operator_top] = operator;
} else if (operator == ')') {
while (operator_top > -1 && operator_stack[operator_top] != '(') {
double num2 = stack[top--];
double num1 = stack[top--];
char op = operator_stack[operator_top--];
stack[++top] = calculate(num1, num2, op);
}
operator_top--;
} else if (operator == '+' || operator == '-') {
while (operator_top > -1 && operator_stack[operator_top] != '(') {
double num2 = stack[top--];
double num1 = stack[top--];
char op = operator_stack[operator_top--];
stack[++top] = calculate(num1, num2, op);
}
operator_stack[++operator_top] = operator;
} else if (operator == '*' || operator == '/') {
while (operator_top > -1 && operator_stack[operator_top] != '(' && operator_stack[operator_top] != '+' && operator_stack[operator_top] != '-') {
double num2 = stack[top--];
double num1 = stack[top--];
char op = operator_stack[operator_top--];
stack[++top] = calculate(num1, num2, op);
}
operator_stack[++operator_top] = operator;
} else if (operator == '^' || operator == 'r') {
while (operator_top > -1 && operator_stack[operator_top] != '(' && operator_stack[operator_top] != '+' && operator_stack[operator_top] != '-' && operator_stack[operator_top] != '*' && operator_stack[operator_top] != '/') {
double num2 = stack[top--];
double num1 = stack[top--];
char op = operator_stack[operator_top--];
stack[++top] = calculate(num1, num2, op);
}
operator_stack[++operator_top] = operator;
} else {
printf("Invalid input\n");
}
}
token = strtok(NULL, " ");
}
while (operator_top > -1) {
double num2 = stack[top--];
double num1 = stack[top--];
char op = operator_stack[operator_top--];
stack[++top] = calculate(num1, num2, op);
}
result = stack[top];
printf("Result: %.2lf\n", result);
clear_input_buffer();
}
return 0;
}
```
这个计算器使用了两个栈,一个用来存储数字,一个用来存储操作符。在读入一个表达式之后,先将其转化为后缀表达式,然后再计算出结果。可以输入多个表达式,直到用户输入 "q" 退出程序。