usaa24/cv3/program.c

112 lines
2.3 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 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");
}
void process_operation(struct stack* s, const char* operation) {
float b = pop_stack(s);
float a = pop_stack(s);
if (strcmp(operation, "+") == 0) {
push_stack(s, a + b);
} else if (strcmp(operation, "-") == 0) {
push_stack(s, a - b);
} else if (strcmp(operation, "*") == 0) {
push_stack(s, a * b);
} else if (strcmp(operation, "/") == 0) {
if (b == 0) {
printf("Chyba: Delenie nulou.\n");
exit(1);
}
push_stack(s, a / b);
}
}
int main() {
struct stack mystack;
init_stack(&mystack);
char input[256];
int has_input = 0;
printf("Poľská kalkulačka\n");
while (1) {
printf("Zadajte číslo alebo operáciu (+, -, *, /): ");
if (!fgets(input, sizeof(input), stdin)) {
break;
}
input[strcspn(input, "\n")] = 0;
char* endptr;
float value = strtof(input, &endptr);
if (endptr != input) {
push_stack(&mystack, value);
has_input = 1;
print_stack(&mystack);
continue;
}
if (strcmp(input, "+") == 0 || strcmp(input, "-") == 0 ||
strcmp(input, "*") == 0 || strcmp(input, "/") == 0) {
if (mystack.size < 2) {
printf("Chyba: Nedostatok hodnôt v zásobníku.\n");
break;
}
process_operation(&mystack, input);
print_stack(&mystack);
} else {
printf("Chyba: Neplatný vstup.\n");
break;
}
}
if (has_input) {
printf("no input\n");
} else {
printf("no input\n");
}
return 0;
}