First try

This commit is contained in:
Anton Dolozin 2025-10-06 13:01:19 +02:00
parent 64c810a801
commit 7dcd74f698

60
du3/program.c Normal file
View File

@ -0,0 +1,60 @@
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <assert.h>
#define STACK_SIZE 10000
struct stack{
float values[STACK_SIZE];
int size;
};
struct stack mystack;
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;
}
void print_stack(struct stack* stack){
for(int i = 0; i < stack->size; i++)
printf("%g ", stack->values[i]);
printf("\n");
}
void process_operations(struct stack* stack){
char line[STACK_SIZE];
if(!fgets(line, STACK_SIZE, stdin)){
printf("Chyba\n");
return;
}
for(int i = 0; line[i] != '\0'; i++){
if(line[i] >= '0' && line[i] <= '9'){
char *endptr;
float val = strtof(&line[i], &endptr);
push_stack(stack, val);
print_stack(stack);
i = endptr - line - 1;
}
else if ((line[i] == '*' || line[i] == '+' || line[i] == '-' || line[i] == '/')
&& stack->size >= 2){
float b = pop_stack(stack);
float a = pop_stack(stack);
float res = (line[i] == '+') ? a + b :
(line[i] == '-') ? a - b :
(line[i] == '*') ? a * b :
(line[i] == '/') ? a / b : 0;
push_stack(stack, res);
print_stack(stack);
}
}
}
int main(void){
memset(&mystack,0,sizeof(struct stack));
process_operations(&mystack);
}