usaa24/cv3/program.c

102 lines
2.4 KiB
C

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_RAZMER 10
typedef struct {
double chisla[MAX_RAZMER];
int vershina;
} StEk;
void inicStEk(StEk* stek) {
stek->vershina = 0;
}
int isEmpty(StEk* stek) {
return stek->vershina == 0;
}
int isFull(StEk* stek) {
return stek->vershina == MAX_RAZMER;
}
void push(StEk* stek, double chislo) {
if (isFull(stek)) {
printf("not enough operands\n");
exit(1);
}
stek->chisla[stek->vershina] = chislo;
stek->vershina++;
}
double pop(StEk* stek) {
if (isEmpty(stek)) {
printf("not enough operands\n");
exit(1);
}
return stek->chisla[--stek->vershina];
}
int main() {
StEk stek;
inicStEk(&stek);
char bufer[256];
while (fgets(bufer, sizeof(bufer), stdin) != NULL) {
if (bufer[0] == '\n') {
if (isEmpty(&stek)) {
printf("no input\n");
} else {
double result = pop(&stek);
printf("%.2lf\n", result);
}
return 0;
}
char* konec;
double chislo = strtod(bufer, &konec);
char c = konec[0];
if (c == '\n' && *bufer != '\n' && *bufer != ' ') {
push(&stek, chislo);
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
if (isEmpty(&stek)) {
printf("not enough operands\n");
return 0;
}
double b = pop(&stek);
if (isEmpty(&stek)) {
printf("not enough operands\n");
return 0;
}
double a = pop(&stek);
if (c == '+') {
push(&stek, a + b);
} else if (c == '-') {
push(&stek, a - b);
} else if (c == '*') {
push(&stek, a * b);
} else if (c == '/') {
if (b == 0) {
printf("division by zero\n");
return 0;
}
push(&stek, a / b);
}
} else if (!isdigit(c) || !isalpha(c)) {
printf("bad input\n");
return 0;
} else {
printf("no input\n");
return 0;
}
for (int i = 0; i < stek.vershina; i++) {
printf("%.2lf ", stek.chisla[i]);
}
printf("\n");
}
printf("no input\n");
return 0;
}