95 lines
2.3 KiB
C
95 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <math.h>
|
|
|
|
#define STACK_SIZE 10
|
|
|
|
struct stack {
|
|
float values[STACK_SIZE];
|
|
int size;
|
|
};
|
|
|
|
int is_operator(const char *str) {
|
|
return (strcmp(str, "+") == 0 ||
|
|
strcmp(str, "-") == 0 ||
|
|
strcmp(str, "*") == 0 ||
|
|
strcmp(str, "/") == 0);
|
|
}
|
|
|
|
void push_stack(struct stack *s, float value) {
|
|
if (s->size >= STACK_SIZE) {
|
|
printf("Chyba: zásobník je plný.\n");
|
|
exit(1);
|
|
}
|
|
s->values[s->size++] = value;
|
|
}
|
|
|
|
void p_stack(struct stack *s) {
|
|
for (int i = 0; i < s->size; i++) {
|
|
|
|
(fabsf(s->values[i] - (int)s->values[i]) < 1e-6) ?
|
|
printf("%d", (int)s->values[i]) :
|
|
printf("%g", s->values[i]);
|
|
|
|
if (i < s->size - 1) printf(" ");
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
void p_number(float value) {
|
|
(fabsf(value - (int)value) < 1e-6) ? printf("%d", (int)value) : printf("%g", value);
|
|
}
|
|
|
|
|
|
float remove_stack(struct stack *s) {
|
|
if (s->size <= 0) {
|
|
printf("Chyba: prazdny zasobnik.\n");
|
|
exit(1);
|
|
}
|
|
return s->values[--s->size];
|
|
}
|
|
|
|
int main() {
|
|
struct stack mystack = { .size = 0 };
|
|
char input[100];
|
|
|
|
while (fgets(input, sizeof(input), stdin)) {
|
|
input[strcspn(input, "\n")] = 0;
|
|
if (!*input) continue;
|
|
|
|
char *endptr;
|
|
float value = strtof(input, &endptr);
|
|
|
|
if (endptr != input && *endptr == '\0') {
|
|
push_stack(&mystack, value);
|
|
p_stack(&mystack);
|
|
} else if (is_operator(input)) {
|
|
if (mystack.size < 2) {
|
|
printf("Chyba: nedostatok hodnôt v zásobníku.\n");
|
|
exit(1);
|
|
}
|
|
|
|
float b = remove_stack(&mystack);
|
|
float a = remove_stack(&mystack);
|
|
|
|
float res = strcmp(input, "+") == 0 ? a + b :
|
|
strcmp(input, "-") == 0 ? a - b :
|
|
strcmp(input, "*") == 0 ? a * b :
|
|
strcmp(input, "/") == 0 ?
|
|
(b == 0 ? (printf("Chyba: delenie nulou.\n"), exit(1), 0) : a / b)
|
|
: 0;
|
|
|
|
push_stack(&mystack, res);
|
|
p_stack(&mystack);
|
|
} else {
|
|
printf("Chyba: neplatný vstup.\n");
|
|
exit(1);
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|