Aktualizovat du3/program.c
This commit is contained in:
parent
782f1340d5
commit
8c11f02f93
@ -0,0 +1,86 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define STACK_SIZE 10
|
||||
#define BUFFER_SIZE 100
|
||||
|
||||
struct stack {
|
||||
float values[STACK_SIZE];
|
||||
int size;
|
||||
};
|
||||
|
||||
void init_stack(struct stack* s) {
|
||||
s->size = 0;
|
||||
}
|
||||
|
||||
int push_stack(struct stack* s, float znac) {
|
||||
if (s->size >= STACK_SIZE) {
|
||||
printf("stack overflow\n");
|
||||
return 0;
|
||||
}
|
||||
s->values[s->size++] = znac;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int pop_stack(struct stack* s, float* out) {
|
||||
if (s->size < 1) {
|
||||
printf("stack underflow\n");
|
||||
return 0;
|
||||
}
|
||||
*out = s->values[--s->size]; //зменшуємо розмір стеку
|
||||
return 1;
|
||||
}
|
||||
|
||||
void print_stack(struct stack* s) {
|
||||
for (int i = 0; i < s->size; i++) {
|
||||
printf("%.2f ", s->values[i]);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main() {
|
||||
struct stack mystack;
|
||||
char buffer[BUFFER_SIZE];
|
||||
char operator;
|
||||
float new, a, b, result;
|
||||
init_stack(&mystack); //обнуляємо стек
|
||||
|
||||
while (fgets(buffer, BUFFER_SIZE, stdin)) {
|
||||
buffer[strcspn(buffer, "\n")] = '\0';
|
||||
if (strlen(buffer) == 0) {
|
||||
printf("no input\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (sscanf(buffer, "%f", &new) == 1) { //спроба прочитати число
|
||||
if (!push_stack(&mystack, new)) return 1;
|
||||
print_stack(&mystack);
|
||||
}else if (sscanf(buffer, " %c", &operator) == 1 && strchr("+-*/", operator)) {
|
||||
if (!pop_stack(&mystack, &b) || !pop_stack(&mystack, &a)) return 1;
|
||||
|
||||
switch (operator) {
|
||||
case '+': result=a+b; break;
|
||||
case '-': result=a-b; break;
|
||||
case '*': result=a*b; break;
|
||||
case '/':
|
||||
if (b == 0) {
|
||||
printf("division by zero\n");
|
||||
return 1;
|
||||
}
|
||||
result = a/b;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!push_stack(&mystack, result)) {
|
||||
return 1;
|
||||
}
|
||||
print_stack(&mystack);
|
||||
} else {
|
||||
printf("invalid input\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
printf("no input\n");
|
||||
return 1;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user