usaa24/cv3/program.c
2024-10-14 15:36:31 +02:00

112 lines
2.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#define STACK_SIZE 50
struct stack
{
float values[STACK_SIZE];
int size;
};
void add(struct stack* stack, float num)
{
assert(stack->size < STACK_SIZE);
stack->values[stack->size] = num;
stack->size++;
}
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)
{
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(isalpha(buf) != 0)
{
printf("bad input\n");
return 0;
}
buf[strcspn(buf, "\n")] = '\0';
if(!check_op(buf[0]))
{
num = atof(buf);
add(&calc_stack, num);
}
else
{
if(calculate(&calc_stack, buf[0]) == 1)
{
printf("division by zero\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;
}