#include #include #include #include #include #define STACK_SIZE 10 struct stack { float values[STACK_SIZE]; int size; }; void init_stack(struct stack* s) { memset(s, 0, sizeof(struct stack)); } void push_stack(struct stack* s, float value) { assert(s->size < STACK_SIZE); s->values[s->size] = value; s->size += 1; } float pop_stack(struct stack* s) { assert(s->size > 0); s->size -= 1; return s->values[s->size]; } void print_stack(struct stack* s) { for (int i = 0; i < s->size; i++) { printf("%.2f ", s->values[i]); } printf("\n"); } int is_number(const char* str) { char* endptr; strtof(str, &endptr); return endptr != str && *endptr == '\0'; } int main() { struct stack mystack; init_stack(&mystack); char input[20]; while (1) { printf("Enter a number or an operation (+, -, *, /): "); if (!fgets(input, sizeof(input), stdin)) { break; } input[strcspn(input, "\n")] = 0; if (is_number(input)) { float value = strtof(input, NULL); push_stack(&mystack, value); print_stack(&mystack); } else { if (mystack.size < 2) { printf("Error: Not enough values on the stack to perform operation.\n"); break; } float b = pop_stack(&mystack); float a = pop_stack(&mystack); float result; switch (input[0]) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': if (b == 0) { printf("Error: Division by zero.\n"); break; } result = a / b; break; default: printf("Error: Unknown operation '%s'.\n", input); push_stack(&mystack, a); push_stack(&mystack, b); break; } if (result) { push_stack(&mystack, result); print_stack(&mystack); } } } return 0; }