usaa24/cv3/program.c

113 lines
2.7 KiB
C
Raw Normal View History

2024-10-07 12:38:16 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define STACK_SIZE 10
2024-10-17 11:38:16 +00:00
2024-10-07 12:38:16 +00:00
struct stack {
float values[STACK_SIZE];
int size;
};
2024-10-17 11:38:16 +00:00
void init_stack(struct stack* s) {
memset(s, 0, sizeof(struct stack));
}
void push_stack(struct stack* s, float value) {
assert(s->size < STACK_SIZE);
s->values[s->size] = value;
s->size += 1;
}
float pop_stack(struct stack* s) {
assert(s->size > 0);
s->size -= 1;
return s->values[s->size];
}
void print_stack(struct stack* s) {
for (int i = 0; i < s->size; i++) {
printf("%.2f ", s->values[i]);
}
printf("\n");
}
2024-10-07 12:38:16 +00:00
int main() {
struct stack mystack;
2024-10-17 11:38:16 +00:00
init_stack(&mystack);
2024-10-07 12:38:16 +00:00
2024-10-17 11:38:16 +00:00
char input[256];
2024-10-07 12:38:16 +00:00
while (1) {
2024-10-17 11:38:16 +00:00
printf("Zadajte číslo alebo operáciu (+, -, *, /): ");
2024-10-07 12:38:16 +00:00
if (!fgets(input, sizeof(input), stdin)) {
2024-10-17 11:15:27 +00:00
break;
2024-10-07 12:38:16 +00:00
}
2024-10-17 11:38:16 +00:00
input[strcspn(input, "\n")] = 0;
2024-10-17 11:20:43 +00:00
2024-10-17 11:38:16 +00:00
char* endptr;
float value = strtof(input, &endptr);
if (endptr != input) {
push_stack(&mystack, value);
print_stack(&mystack);
continue;
2024-10-07 12:43:15 +00:00
}
2024-10-17 11:38:16 +00:00
if (strcmp(input, "+") == 0) {
2024-10-07 12:43:15 +00:00
if (mystack.size < 2) {
2024-10-17 11:38:16 +00:00
printf("Chyba: Nedostatok hodnôt v zásobníku.\n");
break;
2024-10-07 12:43:15 +00:00
}
2024-10-07 12:38:16 +00:00
float b = pop_stack(&mystack);
float a = pop_stack(&mystack);
2024-10-17 11:38:16 +00:00
push_stack(&mystack, a + b);
print_stack(&mystack);
} else if (strcmp(input, "-") == 0) {
if (mystack.size < 2) {
printf("Chyba: Nedostatok hodnôt v zásobníku.\n");
break;
2024-10-07 12:38:16 +00:00
}
2024-10-17 11:38:16 +00:00
float b = pop_stack(&mystack);
float a = pop_stack(&mystack);
push_stack(&mystack, a - b);
print_stack(&mystack);
} else if (strcmp(input, "*") == 0) {
if (mystack.size < 2) {
printf("Chyba: Nedostatok hodnôt v zásobníku.\n");
break;
}
float b = pop_stack(&mystack);
float a = pop_stack(&mystack);
push_stack(&mystack, a * b);
print_stack(&mystack);
} else if (strcmp(input, "/") == 0) {
if (mystack.size < 2) {
printf("Chyba: Nedostatok hodnôt v zásobníku.\n");
break;
}
float b = pop_stack(&mystack);
float a = pop_stack(&mystack);
if (b == 0) {
printf("Chyba: Delenie nulou.\n");
break;
}
push_stack(&mystack, a / b);
print_stack(&mystack);
2024-10-07 12:38:16 +00:00
} else {
2024-10-17 11:38:16 +00:00
printf("Chyba: Neplatný vstup.\n");
break;
2024-10-07 12:38:16 +00:00
}
2024-10-17 11:32:53 +00:00
}
2024-10-07 12:38:16 +00:00
return 0;
}