usaa24/cv3/program.c

82 lines
1.5 KiB
C
Raw Normal View History

2024-10-07 12:38:16 +00:00
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 10
2024-10-17 12:19:39 +00:00
double stack[STACK_SIZE];
int top = 0;
2024-10-17 12:02:05 +00:00
2024-10-17 12:19:39 +00:00
void print_stack() {
for (int i = 0; i < top; i++) {
printf("%.2f ", stack[i]);
}
printf("\n");
2024-10-17 11:38:16 +00:00
}
2024-10-17 12:19:39 +00:00
int push(double value) {
if (top >= STACK_SIZE) {
printf("full stack\n");
return 0;
}
stack[top++] = value;
print_stack();
return 1;
2024-10-17 11:38:16 +00:00
}
2024-10-17 12:19:39 +00:00
int pop(double *value) {
if (top <= 0) {
printf("not enough operands\n");
return 0;
}
*value = stack[--top];
return 1;
2024-10-17 11:38:16 +00:00
}
2024-10-17 12:19:39 +00:00
int apply_operation(char op) {
double a, b;
2024-10-17 12:02:05 +00:00
2024-10-17 12:19:39 +00:00
if (!pop(&b) || !pop(&a)) {
return 0;
2024-10-17 11:38:16 +00:00
}
2024-10-07 12:38:16 +00:00
2024-10-17 12:19:39 +00:00
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;
}
2024-10-17 12:02:05 +00:00
2024-10-17 12:19:39 +00:00
return push(result);
2024-10-17 11:58:16 +00:00
}
2024-10-07 12:38:16 +00:00
int main() {
2024-10-17 12:19:39 +00:00
char input[100];
2024-10-07 12:38:16 +00:00
2024-10-17 12:19:39 +00:00
while (scanf("%s", input) == 1) {
char *end;
double value = strtod(input, &end);
2024-10-17 11:20:43 +00:00
2024-10-17 12:19:39 +00:00
if (*end == '\0') {
if (!push(value)) return 0;
} else if (input[1] == '\0' && strchr("+-*/", input[0])) {
if (!apply_operation(input[0])) return 0;
2024-10-17 12:07:00 +00:00
} else {
2024-10-17 12:19:39 +00:00
printf("bad input\n");
return 0;
2024-10-17 12:07:00 +00:00
}
2024-10-17 11:41:41 +00:00
}
2024-10-17 12:19:39 +00:00
printf("no input\n");
2024-10-07 12:38:16 +00:00
return 0;
}