This commit is contained in:
Alina Konoval 2025-10-12 14:50:40 +02:00
parent b19619d4bb
commit 033344b513

View File

@ -1,93 +1,61 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <math.h>
#define STACK_SIZE 10 #define SIZE 10
struct stack { int main(void) {
float values[STACK_SIZE]; double ulozisko[SIZE];
int size; int top = 0;
}; char vstup[64];
int is_operator(const char *str) { while (fgets(vstup, sizeof(vstup), stdin)) {
return (strcmp(str, "+") == 0 || vstup[strcspn(vstup, "\n")] = 0;
strcmp(str, "-") == 0 ||
strcmp(str, "*") == 0 ||
strcmp(str, "/") == 0);
}
void push_stack(struct stack *s, float value) { if (strlen(vstup) == 0) {
if (s->size >= STACK_SIZE) { printf("no input\n");
printf("Chyba: zásobník je plný.\n"); return 0;
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");
}
float remove_stack(struct stack *s) {
if (s->size <= 0) {
printf("Chyba: prázdny zásobník.\n");
exit(1);
}
return s->values[--s->size];
}
int main() {
struct stack mystack = { .size = 0 };
char input[100];
while (1) {
printf("> ");
fflush(stdout);
if (!fgets(input, sizeof(input), stdin)) break;
input[strcspn(input, "\n")] = 0;
if (!*input) {
printf("no input \n");
break;
} }
char *endptr; char *koniec;
float value = strtof(input, &endptr); double cislo = strtod(vstup, &koniec);
if (endptr != input && *endptr == '\0') { if (*koniec == '\0') {
push_stack(&mystack, value); if (top >= SIZE) {
p_stack(&mystack); printf("stack full\n");
} else if (is_operator(input)) { return 0;
if (mystack.size < 2) { }
printf("Chyba: nedostatok hodnôt v zásobníku.\n"); ulozisko[top++] = cislo;
exit(1); }
else if (strlen(vstup) == 1 && strchr("+-*/", vstup[0])) {
if (top < 2) {
printf("not enough values\n");
return 0;
}
double b = ulozisko[--top];
double a = ulozisko[--top];
double vysledok = 0.0;
switch (vstup[0]) {
case '+': vysledok = a + b; break;
case '-': vysledok = a - b; break;
case '*': vysledok = a * b; break;
case '/': vysledok = b == 0 ? (printf("divide by zero\n"), exit(0), 0) : a / b; break;
default: printf("invalid op\n"); return 0;
} }
float b = remove_stack(&mystack); ulozisko[top++] = vysledok;
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);
} }
else {
printf("invalid input\n");
return 0;
}
for (int i = 0; i < top; i++)
printf("%.2f ", ulozisko[i]);
printf("\n");
} }
printf("no input\n");
return 0; return 0;
} }