usaa25/du3/program.c

87 lines
2.2 KiB
C

#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <assert.h>
#define STACK_SIZE 10000
struct stack{
float values[STACK_SIZE];
int size;
};
struct stack mystack;
void push_stack(struct stack* stack, float value){
assert(stack->size < STACK_SIZE);
stack->values[stack->size] = value;
stack->size += 1;
}
float pop_stack(struct stack* stack){
assert(stack->size > 0);
float value = stack->values[stack->size-1];
stack->size -= 1;
return value;
}
void print_stack(struct stack* stack){
for(int i = 0; i < stack->size; i++)
printf("%.2f ", stack->values[i]);
printf("\n");
}
void process_operations(struct stack* stack) {
char line[STACK_SIZE];
int could_read = 0;
while (fgets(line, sizeof(line), stdin)) {
could_read= 1;
line[strcspn(line, "\n")] = '\0';
if (line == '\0')
{printf("no input\n");
return;
}
if ((strcmp(line, "+") == 0 || strcmp(line, "-") == 0 ||
strcmp(line, "*") == 0 || strcmp(line, "/") == 0)) {
if (stack->size >= 2) {
float b = pop_stack(stack);
float a = pop_stack(stack);
if (line[0] == '/' && b == 0.0F)
{
printf("division by zero\n");
return;
}
float res = (line[0] == '+') ? a + b :
(line[0] == '-') ? a - b :
(line[0] == '*') ? a * b :
(line[0] == '/') ? a / b : 0;
push_stack(stack, res);
print_stack(stack);
} else {
printf("bad input\n");
return;
}
} else {
char *endptr;
float val = strtof(line, &endptr);
if (endptr == line) {
printf("no input\n");
return;
}
push_stack(stack, val);
print_stack(stack);
}
}
if (!could_read) {
printf("no input\n");
}
printf("no input\n");
}
int main(void){
memset(&mystack,0,sizeof(struct stack));
process_operations(&mystack);
}