usaa24/cv3/program.c

82 lines
1.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 10
double stack[STACK_SIZE];
int top = 0;
void print_stack() {
for (int i = 0; i < top; i++) {
printf("%.2f ", stack[i]);
}
printf("\n");
}
int push(double value) {
if (top >= STACK_SIZE) {
printf("full stack\n");
return 0;
}
stack[top++] = value;
print_stack();
return 1;
}
int pop(double *value) {
if (top <= 0) {
printf("not enough operands\n");
return 0;
}
*value = stack[--top];
return 1;
}
int apply_operation(char op) {
double a, b;
if (!pop(&b) || !pop(&a)) {
return 0;
}
double result;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/':
if (b == 0) {
printf("division by zero\n");
return 0;
}
result = a / b;
break;
default:
printf("bad input\n");
return 0;
}
return push(result);
}
int main() {
char input[100];
while (scanf("%s", input) == 1) {
char *end;
double value = strtod(input, &end);
if (*end == '\0') {
if (!push(value)) return 0;
} else if (input[1] == '\0' && strchr("+-*/", input[0])) {
if (!apply_operation(input[0])) return 0;
} else {
printf("bad input\n");
return 0;
}
}
printf("no input\n");
return 0;
}