113 lines
2.4 KiB
C
113 lines
2.4 KiB
C
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <stdbool.h>
|
|
|
|
#define STACK_SIZE 10
|
|
|
|
float stack[STACK_SIZE];
|
|
int stack_top = -1;
|
|
|
|
bool is_number(char *string) {
|
|
char *end;
|
|
strtof(string, &end);
|
|
return end != string && (*end == '\n' || *end == '\0');
|
|
}
|
|
|
|
bool is_operation(char *string) {
|
|
return strlen(string) == 2 && (string[0] == '+' || string[0] == '-' || string[0] == '*' || string[0] == '/');
|
|
}
|
|
|
|
float calculator(float n1, float n2, char operation) {
|
|
if (operation == '+') {
|
|
return n1 + n2;
|
|
}
|
|
else if (operation == '-') {
|
|
return n1 - n2;
|
|
}
|
|
else if (operation == '*') {
|
|
return n1 * n2;
|
|
}
|
|
else if (operation == '/') {
|
|
if (n2 != 0) {
|
|
return n1 / n2;
|
|
} else {
|
|
printf("Error: division by zero\n");
|
|
return 0;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
void push(float number) {
|
|
if (stack_top < STACK_SIZE - 1) {
|
|
stack[++stack_top] = number;
|
|
} else {
|
|
printf("Error: stack overflow\n");
|
|
}
|
|
}
|
|
|
|
float pop() {
|
|
if (stack_top >= 0) {
|
|
return stack[stack_top--];
|
|
} else {
|
|
printf("Error: stack is empty\n");
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
char arr[50];
|
|
char *pend;
|
|
stack_top = -1;
|
|
bool first_output = true;
|
|
|
|
while (fgets(arr, 50, stdin)) {
|
|
if (arr[0] == '\n' || arr[0] == EOF) {
|
|
break;
|
|
}
|
|
|
|
if (is_number(arr)) {
|
|
float number = strtof(arr, &pend);
|
|
push(number);
|
|
if (!first_output) {
|
|
printf(" ");
|
|
}
|
|
printf("%.2f", number);
|
|
first_output = false;
|
|
}
|
|
else if (is_operation(arr)) {
|
|
if (stack_top < 1) {
|
|
if (!first_output) {
|
|
printf("\n");
|
|
}
|
|
printf("no input\n");
|
|
return 0;
|
|
}
|
|
|
|
float n2 = pop();
|
|
float n1 = pop();
|
|
char operation = arr[0];
|
|
float result = calculator(n1, n2, operation);
|
|
push(result);
|
|
if (!first_output) {
|
|
printf(" ");
|
|
}
|
|
printf("%.2f", result);
|
|
first_output = false;
|
|
}
|
|
}
|
|
|
|
if (stack_top == 0) {
|
|
if (!first_output) {
|
|
printf(" ");
|
|
}
|
|
printf("\n%.2f\n", pop());
|
|
} else {
|
|
printf("\nno input\n");
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|