Initializacia

This commit is contained in:
Kozar 2024-10-13 09:13:29 +00:00
parent d525b29472
commit bc1099ece9

View File

@ -1,40 +1,104 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include<ctype.h>
#include <assert.h> #include <assert.h>
#include <ctype.h>
#define LINE_SIZE 100 #define LINE_SIZE 100
#define STACK_SIZE 100 #define STACK_SIZE 10
struct stack { struct stack {
float values[LINE_SIZE]; float values[STACK_SIZE];
int size; int size;
}; };
void print_stack(struct stack* stack) { void print_stack(struct stack* stack) {
for (int i = 0; i < stack->size; i++) { for (int i = 0; i < stack->size; i++) {
printf("%.0f", stack->values[i]); printf("%.2f ", stack->values[i]);
} }
printf("\n"); printf("\n");
} }
void push_stack(struct stack* stack, float value) {
if (stack->size >= STACK_SIZE) {
printf("Chyba: zasobnik je plny\n");
exit(1);
}
stack->values[stack->size] = value;
stack->size++;
}
float pop_stack(struct stack* stack) {
if (stack->size == 0) {
printf("Chyba: zasobnik je prazdny\n");
exit(1);
}
stack->size--;
return stack->values[stack->size];
}
int is_operator(char* input) {
return (strcmp(input, "+") == 0 || strcmp(input, "-") == 0 ||
strcmp(input, "*") == 0 || strcmp(input, "/") == 0);
}
void perform_operation(struct stack* stack, char* operator) {
if (stack->size < 2) {
printf("Chyba: nedostatok operandov\n");
exit(1);
}
float b = pop_stack(stack);
float a = pop_stack(stack);
float result;
if (strcmp(operator, "+") == 0) {
result = a + b;
} else if (strcmp(operator, "-") == 0) {
result = a - b;
} else if (strcmp(operator, "*") == 0) {
result = a * b;
} else if (strcmp(operator, "/") == 0) {
if (b == 0) {
printf("Chyba: delenie nulou\n");
exit(1);
}
result = a / b;
} else {
printf("Chyba: neplatna operacia\n");
exit(1);
}
push_stack(stack, result);
}
int main() { int main() {
char input[LINE_SIZE]; float y; struct stack mystack; char input[LINE_SIZE];
float value;
struct stack mystack;
memset(&mystack, 0, sizeof(struct stack)); memset(&mystack, 0, sizeof(struct stack));
while (fgets(input, LINE_SIZE, stdin) != NULL) { while (fgets(input, LINE_SIZE, stdin) != NULL) {
input[strlen(input - 1)] = '\0'; // Remove trailing newline character
if(sscanf(input, "\f", &y) == 1){ input[strlen(input) - 1] = '\0';
printf("Success!\n");
assert(mystack.size < STACK_SIZE); // Try to parse input as a number
mystack.values[mystack.size] = y; if (sscanf(input, "%f", &value) == 1) {
mystack.size ++; push_stack(&mystack, value);
} else{ }
// If it's not a number, check if it's a valid operator
else if (is_operator(input)) {
perform_operation(&mystack, input);
}
// Invalid input
else {
printf("Chyba: neplatny vstup\n");
return 1; return 1;
} }
// Print stack after each input
print_stack(&mystack); print_stack(&mystack);
} }
return 0; return 0;
} }