95 lines
1.7 KiB
C
95 lines
1.7 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;
|
|
}
|
|
|
|
|
|
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 '-':
|
|
res = num1-num2;
|
|
break;
|
|
case '*':
|
|
res = num1*num2;
|
|
break;
|
|
case '/':
|
|
res = num1/num2;
|
|
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')
|
|
{
|
|
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++)
|
|
{
|
|
printf("%f ", calc_stack.values[i]);
|
|
}
|
|
printf("\n");
|
|
// if (scanf("%f", &num) != 1)
|
|
// {
|
|
// break;
|
|
// }
|
|
|
|
//getchar();
|
|
}
|
|
return 0;
|
|
}
|