usaa24/cv3/program.c
2024-10-13 09:42:19 +00:00

100 lines
2.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define STACK_SIZE 10
struct stack {
float values[STACK_SIZE];
int size;
};
void print_stack(struct stack* s) {
for (int i = 0; i < s->size; i++) {
printf("%.2f", s->values[i]);
if (i < s->size - 1) {
printf(" ");
} else {
printf(" ");
}
}
printf("\n");
}
void push_stack(struct stack* s, float value) {
if (s->size >= STACK_SIZE) {
printf("Chyba: zasobnik je plny\n");
exit(0);
}
s->values[s->size++] = value;
}
float pop_stack(struct stack* s) {
if (s->size == 0) {
printf("Chyba: zasobnik je prazdny\n");
exit(0);
}
return s->values[--s->size];
}
int is_operator(char* input) {
return (strcmp(input, "+") == 0 || strcmp(input, "-") == 0 ||
strcmp(input, "*") == 0 || strcmp(input, "/") == 0);
}
void perform_operation(struct stack* s, char* operator) {
if (s->size < 2) {
printf("Chyba: nedostatok operandov\n");
exit(0);
}
float b = pop_stack(s);
float a = pop_stack(s);
float result;
if (strcmp(operator, "+") == 0) {
result = a + b;
} else if (strcmp(operator, "-") == 0) {
result = a - b;
} else if (strcmp(operator, "*") == 0) {
result = a * b;
} else if (strcmp(operator, "/") == 0) {
if (b == 0) {
printf("division by zero\n");
exit(0);
}
result = a / b;
} else {
printf("Chyba: neplatna operacia\n");
exit(0);
}
push_stack(s, result);
}
int main() {
char input[100];
struct stack mystack;
mystack.size = 0;
while (fgets(input, sizeof(input), stdin) != NULL) {
input[strlen(input) - 1] = '\0';
float value;
if (sscanf(input, "%f", &value) == 1) {
push_stack(&mystack, value);
} else if (is_operator(input)) {
perform_operation(&mystack, input);
} else {
printf("bad input\n");
return 0;
}
print_stack(&mystack);
}
printf("no input\n");
return 0;
}