108 lines
2.6 KiB
C
108 lines
2.6 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 push_stack(struct stack *s, float value){
|
|
if (s->size >= STACK_SIZE){
|
|
printf("Chyba: zasobnik je plny!\n");
|
|
exit(1);
|
|
}
|
|
s->values[s->size] = value;
|
|
s->size++;
|
|
}
|
|
|
|
float pop_stack(struct stack *s){
|
|
if (s->size <= 0){
|
|
printf("Chyba: zasobnik je prazdny!\n");
|
|
exit(1);
|
|
}
|
|
s->size--;
|
|
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");
|
|
}
|
|
|
|
int main(){
|
|
struct stack s;
|
|
s.size = 0;
|
|
|
|
char input[100];
|
|
|
|
while (1){
|
|
if (scanf("%s", input) != 1){
|
|
printf("Chyba: nepodarilo sa nacitat vstup.\n");
|
|
return 1;
|
|
}
|
|
|
|
char *endptr;
|
|
float value = strtof(input, &endptr);
|
|
|
|
if (*endptr == '\0') {
|
|
push_stack(&s, value);
|
|
print_stack(&s);
|
|
}
|
|
else if (strcmp(input, "+") == 0){
|
|
if (s.size < 2){
|
|
printf("Chyba: malo hodnot v zasobniku!\n");
|
|
return 1;
|
|
}
|
|
float b = pop_stack(&s);
|
|
float a = pop_stack(&s);
|
|
push_stack(&s, a + b);
|
|
print_stack(&s);
|
|
}
|
|
else if (strcmp(input, "-") == 0){
|
|
if (s.size < 2){
|
|
printf("Chyba: malo hodnot v zasobniku!\n");
|
|
return 1;
|
|
}
|
|
float b = pop_stack(&s);
|
|
float a = pop_stack(&s);
|
|
push_stack(&s, a - b);
|
|
print_stack(&s);
|
|
}
|
|
else if (strcmp(input, "*") == 0){
|
|
if (s.size < 2){
|
|
printf("Chyba: malo hodnot v zasobniku!\n");
|
|
return 1;
|
|
}
|
|
float b = pop_stack(&s);
|
|
float a = pop_stack(&s);
|
|
push_stack(&s, a * b);
|
|
print_stack(&s);
|
|
}
|
|
else if (strcmp(input, "/") == 0){
|
|
if (s.size < 2){
|
|
printf("Chyba: malo hodnot v zasobniku!\n");
|
|
return 1;
|
|
}
|
|
float b = pop_stack(&s);
|
|
float a = pop_stack(&s);
|
|
if (b == 0){
|
|
printf("Chyba: delenie nulou!\n");
|
|
return 1;
|
|
}
|
|
push_stack(&s, a / b);
|
|
print_stack(&s);
|
|
}
|
|
else{
|
|
printf("Chyba: neplatny vstup '%s'\n", input);
|
|
return 1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|