用c语言编写进行四则混合运算的计算器代码
时间: 2023-10-07 08:13:23 浏览: 216
以下是使用 C 语言编写的进行四则混合运算的计算器代码。
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_INIT_SIZE 20
#define STACK_INCREMENT 10
typedef struct {
float *base;
float *top;
int stackSize;
} Stack;
void InitStack(Stack *S) {
S->base = (float *) malloc(STACK_INIT_SIZE * sizeof(float));
if(!S->base) exit(0);
S->top = S->base;
S->stackSize = STACK_INIT_SIZE;
}
void Push(Stack *S, float e) {
if(S->top - S->base >= S->stackSize) {
S->base = (float *) realloc(S->base, (S->stackSize + STACK_INCREMENT) * sizeof(float));
if(!S->base) exit(0);
S->top = S->base + S->stackSize;
S->stackSize += STACK_INCREMENT;
}
*(S->top) = e;
S->top++;
}
void Pop(Stack *S, float *e) {
if(S->top == S->base) return;
S->top--;
*e = *(S->top);
}
float GetTop(Stack *S) {
if(S->top != S->base) {
return *(S->top - 1);
}
return 0;
}
int IsOperator(char c) {
if(c == '+' || c == '-' || c == '*' || c == '/') {
return 1;
}
return 0;
}
int Priority(char c) {
switch(c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
float Calculate(float num1, float num2, char operator) {
float result;
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if(num2 == 0) {
printf("错误:除数不能为零");
exit(0);
} else {
result = num1 / num2;
}
break;
default:
break;
}
return result;
}
float CalculatePostfix(char* postfix) {
Stack S;
InitStack(&S);
int i = 0;
char c;
float num1, num2, result;
while((c = postfix[i++]) != '\0') {
if(isdigit(c)) {
Push(&S, c - '0');
} else if(IsOperator(c)) {
Pop(&S, &num2);
Pop(&S, &num1);
result = Calculate(num1, num2, c);
Push(&S, result);
}
}
Pop(&S, &result);
return result;
}
int main() {
Stack S;
InitStack(&S);
char infix[100];
char postfix[100];
printf("请输入一个四则运算表达式:");
scanf("%s", infix);
int i = 0, j = 0;
char c;
while((c = infix[i++]) != '\0') {
if(isdigit(c)) {
postfix[j++] = c;
} else if(IsOperator(c)) {
while(Priority(GetTop(&S)) >= Priority(c)) {
Pop(&S, &postfix[j++]);
}
Push(&S, c);
} else if(c == '(') {
Push(&S, c);
} else if(c == ')') {
while(GetTop(&S) != '(') {
Pop(&S, &postfix[j++]);
}
float tmp;
Pop(&S, &tmp);
}
}
while(S.top != S.base) {
Pop(&S, &postfix[j++]);
}
postfix[j] = '\0';
printf("后缀表达式为:%s\n", postfix);
printf("计算结果为:%.2f", CalculatePostfix(postfix));
return 0;
}
```
这个计算器可以将输入的中缀四则运算表达式转化为后缀表达式并计算出结果。
阅读全文