103 lines
2.3 KiB
C
103 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#define STACK_SIZE 10
|
|
|
|
struct stack{
|
|
float *values;
|
|
int size;
|
|
int capacity;
|
|
};
|
|
|
|
struct stack* create_stack (int capacity) {
|
|
struct stack* s = malloc (sizeof(struct stack));
|
|
if (s==NULL) {
|
|
printf("Error!\n");
|
|
exit(1);
|
|
}
|
|
s->values = malloc(capacity * sizeof(float));
|
|
if (s->values==NULL) {
|
|
printf("Error!\n");
|
|
free(s);
|
|
exit(1);
|
|
}
|
|
s->size = 0;
|
|
s->capacity = capacity;
|
|
return s;
|
|
}
|
|
|
|
void push_stack(struct stack* s, float value) {
|
|
if (s->size >= s->capacity) {
|
|
printf("Stack perepolnen!\n");
|
|
exit(1);
|
|
}
|
|
s->values[s->size] = value;
|
|
s->size++;
|
|
}
|
|
|
|
float pop_stack(struct stack* s) {
|
|
if (s->size <= 0) {
|
|
printf("Erroe!\n");
|
|
exit(1);
|
|
}
|
|
s->size--;
|
|
return s->values[s->size];
|
|
}
|
|
|
|
void print_stack(struct stack* stack) {
|
|
for (int i = 0; i<stack->size; i++) {
|
|
printf("%.2f ", stack->values[i]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
void destroy_stack (struct stack* s) {
|
|
free(s->values);
|
|
free(s);
|
|
}
|
|
|
|
int main() {
|
|
struct stack* s = create_stack(STACK_SIZE);
|
|
char input[101];
|
|
while (scanf("%s", input)==1) {
|
|
char *end;
|
|
float value = strtof(input, &end);
|
|
if (*end == '\0') {
|
|
push_stack(s, value);
|
|
print_stack(s);
|
|
} else if (strcmp(input, "+")==0 || strcmp(input, "-")==0 || strcmp(input, "*")==0 || strcmp(input, "/")==0) {
|
|
if (s->size < 2) {
|
|
printf("no input\n");
|
|
destroy_stack(s);
|
|
return 0;
|
|
}
|
|
|
|
float b = pop_stack(s);
|
|
float a = pop_stack(s);
|
|
float result = 0;
|
|
|
|
if (strcmp(input, "+")==0) {
|
|
result = a+b;
|
|
}
|
|
if (strcmp(input, "-")==0) {
|
|
result = a - b;
|
|
}
|
|
if (strcmp(input, "*")==0) {
|
|
result = a * b;
|
|
}
|
|
if (strcmp(input, "/")==0) {
|
|
result = a/b;
|
|
}
|
|
push_stack(s, result);
|
|
print_stack(s);
|
|
}
|
|
else {
|
|
printf("no input");
|
|
destroy_stack(s);
|
|
return 0;
|
|
}
|
|
}
|
|
destroy_stack(s);
|
|
return 0;
|
|
|
|
} |