114 lines
2.6 KiB
C
114 lines
2.6 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <assert.h>
|
|
|
|
#define STACK_SIZE 10
|
|
#define INPUT_SIZE 100
|
|
|
|
// Štruktúra zásobníka
|
|
struct stack {
|
|
float values[STACK_SIZE];
|
|
int size;
|
|
};
|
|
|
|
// Funkcia na vloženie hodnoty do zásobníka (push)
|
|
void push_stack(struct stack* s, float value) {
|
|
if (s->size >= STACK_SIZE) {
|
|
printf("Stack overflow error\n");
|
|
exit(1);
|
|
}
|
|
s->values[s->size] = value;
|
|
s->size += 1;
|
|
}
|
|
|
|
// Funkcia na výber hodnoty zo zásobníka (pop)
|
|
float pop_stack(struct stack* s) {
|
|
if (s->size <= 0) {
|
|
printf("Stack underflow error\n");
|
|
exit(1);
|
|
}
|
|
s->size -= 1;
|
|
return s->values[s->size];
|
|
}
|
|
|
|
// Funkcia na výpis zásobníka
|
|
void print_stack(struct stack* s) {
|
|
for (int i = 0; i < s->size; i++) {
|
|
printf("%.2f ", s->values[i]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
// Funkcia na spracovanie operácií (+, -, *, /)
|
|
void perform_operation(struct stack* s, char op) {
|
|
if (s->size < 2) {
|
|
printf("Not enough values in the stack for operation\n");
|
|
exit(1);
|
|
}
|
|
|
|
float b = pop_stack(s);
|
|
float a = pop_stack(s);
|
|
float result;
|
|
|
|
switch (op) {
|
|
case '+':
|
|
result = a + b;
|
|
break;
|
|
case '-':
|
|
result = a - b;
|
|
break;
|
|
case '*':
|
|
result = a * b;
|
|
break;
|
|
case '/':
|
|
if (b == 0) {
|
|
printf("Division by zero error\n");
|
|
exit(1);
|
|
}
|
|
result = a / b;
|
|
break;
|
|
default:
|
|
printf("Unknown operator\n");
|
|
exit(1);
|
|
}
|
|
|
|
push_stack(s, result);
|
|
}
|
|
|
|
int main() {
|
|
struct stack mystack;
|
|
mystack.size = 0;
|
|
char input[INPUT_SIZE];
|
|
|
|
while (1) {
|
|
// Načítanie vstupu pomocou fgets
|
|
if (fgets(input, sizeof(input), stdin) == NULL) {
|
|
printf("No input\n");
|
|
return 0;
|
|
}
|
|
|
|
// Odstránenie nového riadku (ak existuje)
|
|
input[strcspn(input, "\n")] = 0;
|
|
|
|
// Skúšame, či je vstup číslo
|
|
char *endptr;
|
|
float num = strtof(input, &endptr);
|
|
|
|
if (endptr != input) {
|
|
// Je to číslo, pridáme ho do zásobníka
|
|
push_stack(&mystack, num);
|
|
} else if (strlen(input) == 1 && (input[0] == '+' || input[0] == '-' || input[0] == '*' || input[0] == '/')) {
|
|
// Je to operácia, vykonáme ju
|
|
perform_operation(&mystack, input[0]);
|
|
} else {
|
|
printf("no input\n");
|
|
return 1;
|
|
}
|
|
|
|
// Výpis zásobníka po každom úspešnom vstupe
|
|
print_stack(&mystack);
|
|
}
|
|
|
|
return 0;
|
|
} |