78 lines
1.5 KiB
C
78 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define STACK_SIZE 10
|
|
|
|
struct stack {
|
|
float values[STACK_SIZE];
|
|
int size;
|
|
};
|
|
|
|
void print_stack(struct stack *s) {
|
|
for (int i = 0; i < s->size; i++) {
|
|
printf("%.2f ", s->values[i]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
void push_stack(struct stack *s, float value) {
|
|
if (s->size >= STACK_SIZE) {
|
|
printf("no input\n");
|
|
exit(0);
|
|
}
|
|
s->values[s->size] = value;
|
|
s->size++;
|
|
}
|
|
|
|
float pop_stack(struct stack *s) {
|
|
if (s->size <= 0) {
|
|
printf("no input\n");
|
|
exit(0);
|
|
}
|
|
s->size--;
|
|
return s->values[s->size];
|
|
}
|
|
|
|
int main() {
|
|
struct stack s;
|
|
s.size = 0;
|
|
|
|
char input[100];
|
|
|
|
while (scanf("%s", input) == 1) {
|
|
if (strcmp(input, "+") == 0 || strcmp(input, "-") == 0 ||
|
|
strcmp(input, "*") == 0 || strcmp(input, "/") == 0) {
|
|
|
|
if (s.size < 2) {
|
|
printf("no input\n");
|
|
exit(0);
|
|
}
|
|
|
|
float b = pop_stack(&s);
|
|
float a = pop_stack(&s);
|
|
float result;
|
|
|
|
if (strcmp(input, "+") == 0) result = a + b;
|
|
else if (strcmp(input, "-") == 0) result = a - b;
|
|
else if (strcmp(input, "*") == 0) result = a * b;
|
|
else result = a / b;
|
|
|
|
push_stack(&s, result);
|
|
print_stack(&s);
|
|
}
|
|
else {
|
|
char *endptr;
|
|
float val = strtof(input, &endptr);
|
|
if (*endptr != '\0') {
|
|
printf("no input\n");
|
|
exit(0);
|
|
}
|
|
push_stack(&s, val);
|
|
print_stack(&s);
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|