116 lines
2.7 KiB
C
116 lines
2.7 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <assert.h>
|
|
#include <ctype.h>
|
|
|
|
#define STACK_SIZE 10
|
|
|
|
struct stack {
|
|
float values[STACK_SIZE];
|
|
int size;
|
|
};
|
|
|
|
void push_stack(struct stack* stack, float value);
|
|
float pop_stack(struct stack* stack);
|
|
void print_stack(struct stack* stack);
|
|
int is_number(const char* str);
|
|
|
|
int main() {
|
|
struct stack mystack;
|
|
memset(&mystack, 0, sizeof(struct stack));
|
|
|
|
char input[50];
|
|
int empty_input = 0;
|
|
|
|
while (1) {
|
|
|
|
if (!fgets(input, sizeof(input), stdin)) {
|
|
break;
|
|
}
|
|
|
|
input[strcspn(input, "\n")] = 0;
|
|
|
|
if (strlen(input) == 0) {
|
|
empty_input = 1;
|
|
break;
|
|
}
|
|
|
|
if (is_number(input)) {
|
|
float value = atof(input);
|
|
push_stack(&mystack, value);
|
|
} else if (strlen(input) == 1 && strchr("+-*/", input[0])) {
|
|
if (mystack.size < 2) {
|
|
fprintf(stderr, "Error: Not enough values in stack.\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
float b = pop_stack(&mystack);
|
|
float a = pop_stack(&mystack);
|
|
float result;
|
|
|
|
switch (input[0]) {
|
|
case '+':
|
|
result = a + b;
|
|
break;
|
|
case '-':
|
|
result = a - b;
|
|
break;
|
|
case '*':
|
|
result = a * b;
|
|
break;
|
|
case '/':
|
|
if (b == 0) {
|
|
fprintf(stderr, "Error: Division by zero.\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
result = a / b;
|
|
break;
|
|
default:
|
|
fprintf(stderr, "Error: Invalid operator.\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
push_stack(&mystack, result);
|
|
} else {
|
|
fprintf(stderr, "Error: Invalid input.\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
print_stack(&mystack);
|
|
}
|
|
|
|
|
|
if (empty_input) {
|
|
printf("no input\n");
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
stack->size -= 1;
|
|
return stack->values[stack->size];
|
|
}
|
|
|
|
void print_stack(struct stack* stack) {
|
|
|
|
for (int i = 0; i < stack->size; i++) {
|
|
printf("%.2f ", stack->values[i]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
int is_number(const char* str) {
|
|
char* endptr;
|
|
strtod(str, &endptr);
|
|
return *endptr == '\0' && endptr != str;
|
|
}
|