usaa25/du3/program.c

90 lines
2.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_SIZE 10
#define BUFFER_SIZE 100
struct stack {
float values[STACK_SIZE];
int size;
};
void init_stack(struct stack* s) {
s->size = 0;
}
int push_stack(struct stack* s, float znac) {
if (s->size >= STACK_SIZE) {
printf("full stack\n");
return 0;
}
s->values[s->size++] = znac;
return 1;
}
int pop_stack(struct stack* s, float* out) {
if (s->size < 1) {
printf("not enough operands\n");
return 0;
}
*out = s->values[--s->size]; //зменшуємо розмір стеку
return 1;
}
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 mystack;
char buffer[BUFFER_SIZE];
char operator;
float new, a, b, result;
init_stack(&mystack); //обнуляємо стек
float chyslo;
char symbol;
init_stack(&mystack); //обнуляємо стек
while (fgets(buffer, BUFFER_SIZE, stdin)) {
buffer[strcspn(buffer, "\n")] = '\0';
if (strlen(buffer) == 0) {
printf("no input\n");
return 1;
}
if (sscanf(buffer, " %f %c", &chyslo, &symbol) == 1) { //спроба прочитати число але без символів
new = chyslo;
if (!push_stack(&mystack, new)) return 0;
print_stack(&mystack);
} else if (sscanf(buffer, " %c %c", &operator, &symbol) == 1 && strchr("+-*/", operator)) {
if (!pop_stack(&mystack, &b) || !pop_stack(&mystack, &a)) return 0;
switch (operator) {
case '+': result=a+b; break;
case '-': result=a-b; break;
case '*': result=a*b; break;
case '/':
if (b == 0) {
printf("division by zero\n");
return 0;
}
result = a/b;
break;
}
if (!push_stack(&mystack, result)) {
return 1;
}
print_stack(&mystack);
} else {
printf("bad input\n");
return 0;
}
}
printf("no input\n");
return 0;
}