usaa25/du3/program.c
2025-10-15 18:02:24 +02:00

91 lines
1.6 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#define SIZE 10
struct stack{
float values[SIZE];
int size;
};
void print(struct stack *s)
{
if (s->size == 0){
printf("no input\n");
return;
}
for(int i = 0; i < s->size; i++){
printf("%.2f ", s->values[i]);
}
printf("\n");
}
void push(struct stack *s, float value)
{
assert(s->size < SIZE);
s->values[s->size] = value;
s->size += 1;
}
float pop(struct stack *s)
{
assert(s->size > 0);
s->size -= 1;
return s->values[s->size];
}
int main(){
struct stack mystack;
memset(&mystack,0,sizeof(struct stack));
char x[100];
while(fgets(x, 100, stdin)){
x[strcspn(x, "\n")] = 0;
if (strlen(x) == 0) {
print(&mystack);
continue;
}
char *endptr;
float num = strtof(x, &endptr);
if (*endptr == '\0') { // je cislo
if(mystack.size >= SIZE) {
printf("full stack\n");
return 0;
}
push(&mystack,num);
}
else if(strlen(x) == 1 && strchr("+-/*", x[0])) {
if (mystack.size < 2){
printf("not enough operands\n");
return 0;
}
float a = pop(&mystack);
float b = pop(&mystack);
float result = 0;
switch(x[0]){
case '+': result = b + a; break;
case '-': result = b - a; break;
case '*': result = b * a;break;
case '/':
if(a == 0){
printf("division by zero\n");
return 0;
}
result = b / a;
break;
}
push(&mystack,result);
}
else{
printf("bad input\n");
return 0;
}
print (&mystack);
}
printf("no input\n");
if(mystack.size == 0){
printf("no input\n");
}
return 0;
}