usaa24/cv3/program.c

141 lines
2.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#define STACK_SIZE 10
struct stack
{
float values[STACK_SIZE];
int size;
};
int add(struct stack* stack, float num)
{
if(stack->size == STACK_SIZE)
{
return 1;
}
assert(stack->size < STACK_SIZE);
stack->values[stack->size] = num;
stack->size++;
return 0;
}
float getnpop(struct stack* stack)
{
assert(stack->size > 0);
float value = stack->values[stack->size-1];
stack->size -= 1;
return value;
}
int calculate(struct stack* stack, char operator)
{
if(stack->size < 2)
{
return 2;
}
float num1 = getnpop(stack);
float num2 = getnpop(stack);
float res = 0;
switch(operator)
{
case '+':
res = num1+num2;
break;
case '-':
res = num2-num1;
break;
case '*':
res = num1*num2;
break;
case '/':
if(num1 == 0)
{
//res = 1;
return 1;
}
res = num2/num1;
break;
}
add(stack, res);
return 0;
}
int check_op(char symb)
{
if(symb == '+' || symb == '-' || symb == '*' || symb == '/')
{
return 1;
}
return 0;
}
int main(int argc, char const *argv[])
{
char buf[50];
struct stack calc_stack;
float num = 0;
int s = 0;
memset(buf, 0, 50);
memset(&calc_stack,0,sizeof(struct stack));
while (fgets(buf, 50, stdin) != NULL)
{
if(buf[0] == '\n')
{
break;
}
if(buf[0] == '.')
{
printf("bad input\n");
return 0;
}
for (int i = 0; i < strcspn(buf, "\n"); i++)
{
if(isalpha(buf[i]) != 0)
{
printf("bad input\n");
return 0;
}
}
buf[strcspn(buf, "\n")] = '\0';
if(!check_op(buf[0]))
{
num = atof(buf);
int add_code = add(&calc_stack, num);
if(add_code == 1)
{
printf("full stack\n");
return 0;
}
}
else
{
int calc_code = calculate(&calc_stack, buf[0]);
if(calc_code == 1)
{
printf("division by zero\n");
return 0;
}
else if(calc_code == 2)
{
printf("not enough operands\n");
return 0;
}
}
for (int i = 0; i < calc_stack.size; i++)
{
printf("%.2f ", calc_stack.values[i]);
}
printf("\n");
}
printf("no input\n");
return 0;
}