usaa24/cv3/program.c
2024-10-13 09:13:29 +00:00

105 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define LINE_SIZE 100
#define STACK_SIZE 10
struct stack {
float values[STACK_SIZE];
int size;
};
void print_stack(struct stack* stack) {
for (int i = 0; i < stack->size; i++) {
printf("%.2f ", stack->values[i]);
}
printf("\n");
}
void push_stack(struct stack* stack, float value) {
if (stack->size >= STACK_SIZE) {
printf("Chyba: zasobnik je plny\n");
exit(1);
}
stack->values[stack->size] = value;
stack->size++;
}
float pop_stack(struct stack* stack) {
if (stack->size == 0) {
printf("Chyba: zasobnik je prazdny\n");
exit(1);
}
stack->size--;
return stack->values[stack->size];
}
int is_operator(char* input) {
return (strcmp(input, "+") == 0 || strcmp(input, "-") == 0 ||
strcmp(input, "*") == 0 || strcmp(input, "/") == 0);
}
void perform_operation(struct stack* stack, char* operator) {
if (stack->size < 2) {
printf("Chyba: nedostatok operandov\n");
exit(1);
}
float b = pop_stack(stack);
float a = pop_stack(stack);
float result;
if (strcmp(operator, "+") == 0) {
result = a + b;
} else if (strcmp(operator, "-") == 0) {
result = a - b;
} else if (strcmp(operator, "*") == 0) {
result = a * b;
} else if (strcmp(operator, "/") == 0) {
if (b == 0) {
printf("Chyba: delenie nulou\n");
exit(1);
}
result = a / b;
} else {
printf("Chyba: neplatna operacia\n");
exit(1);
}
push_stack(stack, result);
}
int main() {
char input[LINE_SIZE];
float value;
struct stack mystack;
memset(&mystack, 0, sizeof(struct stack));
while (fgets(input, LINE_SIZE, stdin) != NULL) {
// Remove trailing newline character
input[strlen(input) - 1] = '\0';
// Try to parse input as a number
if (sscanf(input, "%f", &value) == 1) {
push_stack(&mystack, value);
}
// If it's not a number, check if it's a valid operator
else if (is_operator(input)) {
perform_operation(&mystack, input);
}
// Invalid input
else {
printf("Chyba: neplatny vstup\n");
return 1;
}
// Print stack after each input
print_stack(&mystack);
}
return 0;
}