usaa23/cv3/program.c

106 lines
2.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_SIZE 10
struct stack_glavny {
float data[STACK_SIZE];
int size;
};
void initialize(struct stack_glavny* stack) {
stack->size = -1;
}
int push(struct stack_glavny* stack, float value) {
if (stack->size < STACK_SIZE - 1) {
stack->size++;
stack->data[stack->size] = value;
return true;
} else {
return false;
}
}
int pop(struct stack_glavny* stack, float* result) {
if (stack->size >= 0) {
*result = stack->data[stack->size];
stack->size--;
return true;
} else {
return false;
}
}
int operation_insert_result(struct stack_glavny* stack, char operation) {
float operand1, operand2, result;
if (pop(stack, &operand2) && pop(stack, &operand1)) {
switch (operation) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 == 0) {
printf("Chyba: Delenie nulou.\n");
return false;
}
result = operand1 / operand2;
break;
default:
printf("Chyba: Neplatná operácia.\n");
return false;
}
if (!push(stack, result)) {
printf("Chyba: Zásobník je plný.\n");
return false;
}
return true;
} else {
printf("Chyba: Nedostatok operandov pre operáciu.\n");
return false;
}
}
int main() {
struct stack_glavny stack;
initialize(&stack);
char input[20];
while (1) {
if (!fgets(input, sizeof(input), stdin)) {
printf("no␣input");
break;
}
float value;
if (sscanf(input, "%f", &value) == 1) {
if (!push(&stack, value)) {
printf("Chyba: Zásobník je plný.\n");
break;
}
} else if (input[0] == '+' || input[0] == '-' || input[0] == '*' || input[0] == '/') {
if (!operation_insert_result(&stack, input[0])) {
break;
}
} else {
printf("Chyba: Neplatný vstup.\n");
break;
}
for (int i = 0; i <= stack.size; i++) {
printf("%.2f ", stack.data[i]);
}
printf("\n");
}
return 0;
}