usaa21/cv3/program.c

112 lines
3.1 KiB
C
Raw Normal View History

2021-10-21 20:42:33 +00:00
#include <errno.h>
2021-10-21 20:16:34 +00:00
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#define STACK_SIZE 20
struct stack{
float values[STACK_SIZE];
int size;
};
void print_stack(struct stack* stack);
void push_stack(struct stack* stack, float value);
float pop_stack(struct stack* stack);
int count_stack(struct stack* stack);
int main(){
char char_value[STACK_SIZE];
memset(&char_value,0,STACK_SIZE);
float float_value;
char* ptr;
struct stack myStack;
memset(&myStack,0,sizeof(struct stack));
while(1){
ptr = fgets(char_value, STACK_SIZE-1, stdin);
if(ptr != NULL ){
2021-10-21 20:42:33 +00:00
if(char_value[0] == '0'){
push_stack(&myStack,0);
print_stack(&myStack);
printf("\n");
continue;
}
2021-10-21 20:16:34 +00:00
float_value = strtof(char_value, NULL);
if(float_value == 0){
if(char_value[0] == '+'){
float a = pop_stack(&myStack);
float b = pop_stack(&myStack);
float c = a+b;
push_stack(&myStack, c);
print_stack(&myStack);
printf("\n");
}
if(char_value[0] == '-'){
float a = pop_stack(&myStack);
float b = pop_stack(&myStack);
2021-10-21 20:21:32 +00:00
float c = b-a;
2021-10-21 20:16:34 +00:00
push_stack(&myStack, c);
print_stack(&myStack);
printf("\n");
}
if(char_value[0] == '*'){
float a = pop_stack(&myStack);
float b = pop_stack(&myStack);
float c = a*b;
push_stack(&myStack, c);
print_stack(&myStack);
printf("\n");
}
if(char_value[0] == '/'){
float a = pop_stack(&myStack);
2021-10-21 20:42:33 +00:00
if(a == 0){
printf("division by zero\n");
break;
}
2021-10-21 20:16:34 +00:00
float b = pop_stack(&myStack);
2021-10-21 20:22:46 +00:00
float c = b/a;
2021-10-21 20:16:34 +00:00
push_stack(&myStack, c);
print_stack(&myStack);
printf("\n");
}
}else {
2021-10-21 20:42:33 +00:00
2021-10-21 20:16:34 +00:00
push_stack(&myStack, float_value);
print_stack(&myStack);
printf("\n");
}
}else{
2021-10-21 20:21:32 +00:00
puts("no input");
2021-10-21 20:16:34 +00:00
break;
}
}
return 0;
}
void print_stack(struct stack* stack){
for(int i = 0; i < stack->size; i++){
2021-10-21 20:21:32 +00:00
printf("%.2f ",stack->values[i]);
2021-10-21 20:16:34 +00:00
}
}
void push_stack(struct stack* stack, float value){
assert(stack->size < STACK_SIZE);
stack->values[stack->size] = value;
stack->size += 1;
}
float pop_stack(struct stack* stack){
assert(stack->size > 0);
float value = stack->values[stack->size-1];
stack->size -= 1;
return value;
}