106 lines
2.2 KiB
C
106 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
|
|
#define STACK_SIZE 10
|
|
|
|
struct stack {
|
|
float values[STACK_SIZE];
|
|
int size;
|
|
};
|
|
|
|
void push(struct stack* stack,float values){
|
|
if(stack->size < 10){
|
|
stack->values[stack->size] = values;
|
|
stack->size += 1;
|
|
}
|
|
else{
|
|
printf("full stack\n");
|
|
exit(0);
|
|
|
|
}
|
|
}
|
|
|
|
float pop(struct stack *stack){
|
|
if(stack->size > 0){
|
|
float value = stack->values[stack->size-1];
|
|
stack->size -= 1;
|
|
return value;
|
|
}
|
|
else{
|
|
printf("not enough operands\n");
|
|
exit(0);
|
|
}
|
|
}
|
|
|
|
void print_stack(struct stack *stack){
|
|
int i;
|
|
int len = stack->size - 1;
|
|
for(i = 0; i < len; i++){
|
|
printf("%0.2f ", stack->values[i]);
|
|
}
|
|
if(stack->size != 0){
|
|
printf("%0.2f ", stack->values[i]);
|
|
printf("\n");
|
|
}
|
|
}
|
|
|
|
|
|
int main() {
|
|
struct stack mystack;
|
|
memset(&mystack, 0, sizeof(struct stack));
|
|
int i = 0;
|
|
for(i = 0; i < 100; i++){
|
|
|
|
char line[10];
|
|
char *x = fgets(line, 10, stdin);
|
|
float r = 0;
|
|
float z = 0;
|
|
|
|
if(line[1] != 0 && x != NULL){
|
|
|
|
|
|
if(!isdigit(line[0]) && line[0] != '+' && line[0] != '*' && line[0] != '/' && line[0] != '-'){
|
|
printf("bad input\n");
|
|
return 0;
|
|
}
|
|
|
|
if(line[0] == '+'){
|
|
r = pop(&mystack) + pop(&mystack);
|
|
}
|
|
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{
|
|
printf("no input\n");
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|