Update 'cv3/program.c'

This commit is contained in:
Maryna Kravtsova 2020-10-21 14:19:37 +00:00
parent 69f2c49596
commit 27ce4ed117

View File

@ -1,9 +1,9 @@
#include <assert.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h>
#define STACK_SIZE 100 #define STACK_SIZE 10
struct stack { struct stack {
float values[STACK_SIZE]; float values[STACK_SIZE];
@ -11,17 +11,29 @@ struct stack {
}; };
void push(struct stack* stack,float values){ void push(struct stack* stack,float values){
assert(stack->size < STACK_SIZE); if(stack->size < 10){
stack->values[stack->size] = values; stack->values[stack->size] = values;
stack->size += 1; stack->size += 1;
}
else{
printf("full stack\n");
exit(0);
}
} }
float pop(struct stack *stack){ float pop(struct stack *stack){
assert(stack->size > 0); if(stack->size > 0){
float values = stack->values[stack->size-1]; float value = stack->values[stack->size-1];
stack->size -= 1; stack->size -= 1;
return values; return value;
}
else{
printf("not enough operands\n");
exit(0);
}
} }
void print_stack(struct stack *stack){ void print_stack(struct stack *stack){
int i; int i;
int len = stack->size - 1; int len = stack->size - 1;
@ -30,9 +42,8 @@ void print_stack(struct stack *stack){
} }
if(stack->size != 0){ if(stack->size != 0){
printf("%0.2f ", stack->values[i]); printf("%0.2f ", stack->values[i]);
} printf("\n");
printf("\n"); }
} }
@ -40,44 +51,55 @@ int main() {
struct stack mystack; struct stack mystack;
memset(&mystack, 0, sizeof(struct stack)); memset(&mystack, 0, sizeof(struct stack));
int i = 0; int i = 0;
float z; for(i = 0; i < 100; i++){
for(i = 0; i < 10000; i++){
char line[10]; char line[10];
char *x = fgets(line, 10, stdin); char *x = fgets(line, 10, stdin);
float r = 0; float r = 0;
float z = 0;
if(!isdigit(line[0]) && line[0] != '+' && line[0] != '*' && line[0] != '/' && line[0] != '-'){
printf("no input");
return 0;
}
if(line[0] == '+'){ if(line[1] != 0 && x != NULL){
r = pop(&mystack) + pop(&mystack);
}
else if(line[0] == '-'){ if(!isdigit(line[0]) && line[0] != '+' && line[0] != '*' && line[0] != '/' && line[0] != '-'){
z = pop(&mystack); printf("bad input\n");
r = pop(&mystack) - z; return 0;
} }
else if(line[0] == '*'){
r = pop(&mystack) * pop(&mystack); if(line[0] == '+'){
} r = pop(&mystack) + pop(&mystack);
else if(line[0] == '/'){
z = pop(&mystack);
if(z != 0.0){
r = pop(&mystack) / z;
} }
else if(line[0] == '-'){
z = pop(&mystack);
r = pop(&mystack) - z;
}
else if(line[0] == '*'){
r = pop(&mystack) * pop(&mystack);
}
else if(line[0] == '/'){
z = pop(&mystack);
if(z == 0){
printf("division by zero\n");
return 0;
}
else {
r = pop(&mystack) / z;
}
}
else {
r = strtof(line,&x);
}
push(&mystack,r);
print_stack(&mystack);
} }
else{
else { printf("no input\n");
r = strtof(line,&x); return 0;
} }
push(&mystack,r);
print_stack(&mystack);
} }
return 0; return 0;
} }