usaa24/cv3/program.c

90 lines
1.6 KiB
C
Raw Normal View History

2024-10-14 12:20:08 +00:00
#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;
}
float 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 '-':
2024-10-14 12:24:03 +00:00
res = num2-num1;
2024-10-14 12:20:08 +00:00
break;
case '*':
res = num1*num2;
break;
case '/':
2024-10-14 12:24:03 +00:00
res = num2/num1;
2024-10-14 12:20:08 +00:00
break;
}
add(stack, res);
return res;
}
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')
{
2024-10-14 12:29:01 +00:00
printf("no input\n");
2024-10-14 12:20:08 +00:00
break;
}
buf[strcspn(buf, "\n")] = '\0';
num = atof(buf);
if(num != 0)
{
add(&calc_stack, num);
}
else
{
calculate(&calc_stack, buf[0]);
}
for (int i = 0; i < calc_stack.size; i++)
{
2024-10-14 12:29:01 +00:00
printf("%.2f ", calc_stack.values[i]);
2024-10-14 12:20:08 +00:00
}
printf("\n");
}
return 0;
}