usaa25/du3/program.c
2025-10-14 11:17:11 +02:00

105 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define STACK_SIZE 10
#define LINESIZE 100
struct stack {
float values[STACK_SIZE];
int size;
};
//zakladne funkcie
void push_stack(struct stack *s, float value) {
if (s->size >= STACK_SIZE) {
printf("Chyba: zasobnik je plny.\n");
exit(1);
}
s->values[s->size] = value;
s->size++;
}
float pop_stack(struct stack *s) {
if (s->size <= 0) {
printf("Chyba: zasobnik je prazdny.\n");
exit(1);
}
s->size--;
return s->values[s->size];
}
void print_stack(struct stack *s) {
for (int i = 0; i < s->size; i++) {
if (i > 0) printf(" ");
printf("%g", s->values[i]);
}
printf("\n");
}
//pomocne funkcie
//je retazec cislo
int is_number(const char *str) {
char *endptr;
strtof(str, &endptr);
// ak endptr ukazuje na koniec retazca, bolo to cele cislo
return (*str != '\0' && *endptr == '\0');
}
int main(void) {
struct stack s;
memset(&s, 0, sizeof(struct stack));
char line[LINESIZE];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\n")] = '\0';
//preskocit prazdny riadok
if (strlen(line) == 0)
continue;
if (is_number(line)) {
float value = strtof(line, NULL);
push_stack(&s, value);
} else if (strlen(line) == 1 && strchr("+-*/", line[0])) {
//operacia
if (s.size < 2) {
printf("Chyba: nedostatok operandov.\n");
return 1;
}
float b = pop_stack(&s);
float a = pop_stack(&s);
float result;
switch (line[0]) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/':
if (b == 0) {
printf("Chyba: delenie nulou.\n");
return 1;
}
result = a / b; break;
default:
printf("Chyba: neznama operacia.\n");
return 1;
}
push_stack(&s, result);
} else {
printf("Chyba: neplatny vstup.\n");
return 1;
}
print_stack(&s);
}
return 0;
}