usaa24/cv3/program.c
Bohdan Kapliuk fd95b3d553 cv3
2024-10-12 16:32:51 +03:00

73 lines
2.2 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_SIZE 100
struct stack{
float values[STACK_SIZE];
int size;
};
int main(){
struct stack mystack;
memset(&mystack,0,sizeof(struct stack));
char vstup[STACK_SIZE];
int counter = 0;
while(1){
if (fgets(vstup, sizeof(vstup), stdin) == NULL) {
printf("no input\n");
return 0;
}
if(vstup[0] == '-' || vstup[0] == '+' || vstup[0] == '*' || vstup[0] == '/'){
if(counter < 2){
printf("not enough operands\n");
return 0;
}
if(vstup[0] == '-'){
mystack.values[counter-2] = mystack.values[counter-2] - mystack.values[counter-1];
mystack.values[counter-1] = 0;
counter--;
}
if(vstup[0] == '/'){
if(mystack.values[counter-1] == 0){
printf("division by zero\n");
return 0;
}
mystack.values[counter-2] = mystack.values[counter-2] / mystack.values[counter-1];
mystack.values[counter-1] = 0;
counter--;
}
if(vstup[0] == '*'){
mystack.values[counter-2] = mystack.values[counter-2] * mystack.values[counter-1];
mystack.values[counter-1] = 0;
counter--;
}
if(vstup[0] == '+'){
mystack.values[counter-2] = mystack.values[counter-2] + mystack.values[counter-1];
mystack.values[counter-1] = 0;
counter--;
}
}
else{
char *endptr;
float cislo = strtof(vstup, &endptr);
if (endptr == vstup || *endptr != '\n') {
printf("bad input\n");
return 0;
}
mystack.values[counter] = cislo;
counter++;
if(counter > 10){
printf("full stack\n");
return 0;
}
}
mystack.size = counter;
for(int i =0; i < counter;i++){
printf("%.2f ", mystack.values[i]);
}
printf("\n");
}
}