usaa24/cv3/program.c

124 lines
2.6 KiB
C
Raw Normal View History

2024-10-14 19:37:39 +00:00
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
2024-10-14 20:08:56 +00:00
#include <ctype.h>
2024-10-14 20:24:44 +00:00
//// @
2024-10-14 20:26:12 +00:00
#define STACK_SIZE 10
2024-10-14 19:37:39 +00:00
struct Stack
{
float values[STACK_SIZE];
int size;
};
void push_stack(struct Stack* stack, float value);
float pop_stack(struct Stack* stack);
int count_stack(struct Stack* stack);
void push_stack(struct Stack* stack, float value)
{
2024-10-14 20:08:56 +00:00
assert(stack->size < STACK_SIZE);
2024-10-14 19:37:39 +00:00
stack->values[stack->size] = value;
stack->size += 1;
}
float pop_stack(struct Stack* stack)
{
2024-10-14 20:08:56 +00:00
assert(stack->size > 0);
2024-10-14 19:37:39 +00:00
float value = stack->values[stack->size-1];
stack->size -= 1;
return value;
}
int count_stack(struct Stack* stack)
{
2024-10-14 20:18:38 +00:00
return stack->size;
2024-10-14 19:37:39 +00:00
}
void print_stack(struct Stack* stack)
{
for (int i=0; i<stack->size; i++)
{
2024-10-14 19:46:13 +00:00
printf("%.2f ", stack->values[i]);
2024-10-14 19:37:39 +00:00
}
2024-10-14 19:46:13 +00:00
printf("\n");
2024-10-14 19:37:39 +00:00
}
int main()
{
struct Stack mystack;
mystack.size=0;
//memset(&mystack,0,sizeof(struct Stack));
2024-10-14 19:58:34 +00:00
int err=0;
2024-10-14 19:37:39 +00:00
char buf[505];
do
{
char* p=fgets(buf, 299, stdin);
2024-10-14 20:08:56 +00:00
if(p)
2024-10-14 19:37:39 +00:00
{
char c=buf[0];
float op1, op2, rez;
2024-10-14 20:08:56 +00:00
if(c=='+'||c=='-'||c=='/'||c=='*')
2024-10-14 19:37:39 +00:00
{
2024-10-14 20:18:38 +00:00
if(count_stack(&mystack)<2)
{
printf("not enough operands\n");
err=3;
break;
}
2024-10-14 19:37:39 +00:00
op2=pop_stack(&mystack);
op1=pop_stack(&mystack);
switch(c)
{
case '+': rez=op1+op2; break;
case '-': rez=op1-op2; break;
2024-10-14 19:58:34 +00:00
case '/':
if(c=='/' && op2==0)
{
err=1;
2024-10-14 20:02:40 +00:00
printf("division by zero\n");
2024-10-14 19:58:34 +00:00
}
else
rez=op1/op2;
break;
2024-10-14 19:37:39 +00:00
case '*': rez=op1*op2; break;
2024-10-14 20:08:56 +00:00
}
2024-10-14 19:37:39 +00:00
}
else
2024-10-14 19:46:13 +00:00
{
2024-10-14 20:08:56 +00:00
if(isdigit(c))
2024-10-14 20:24:44 +00:00
{
2024-10-14 20:08:56 +00:00
rez=atof(buf);
2024-10-14 20:24:44 +00:00
}
2024-10-14 20:08:56 +00:00
else
{
err=1;
printf("bad input\n");
}
2024-10-14 19:46:13 +00:00
}
2024-10-14 19:58:34 +00:00
if(!err)
{
2024-10-14 20:24:44 +00:00
if(count_stack(&mystack)==STACK_SIZE)
{
printf("full stack\n");
err=4;
break;
}
2024-10-14 19:58:34 +00:00
push_stack(&mystack, rez);
print_stack(&mystack);
}
2024-10-14 19:37:39 +00:00
}
2024-10-14 20:18:38 +00:00
else break;
2024-10-14 19:37:39 +00:00
}while(1);
2024-10-14 19:58:34 +00:00
if(!err)
printf("no input\n");
2024-10-14 19:37:39 +00:00
return 0;
2024-10-14 20:08:56 +00:00
}