Update cv3/program.c

This commit is contained in:
Marat Izmailov 2024-10-17 12:07:00 +00:00
parent 4dd11b3bae
commit 97831ba7b6

View File

@ -2,6 +2,7 @@
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define STACK_SIZE 10
@ -18,7 +19,7 @@ void init_stack(struct stack* s) {
void push_stack(struct stack* s, float value) {
assert(s->size < STACK_SIZE);
assert(s->size < STACK_SIZE); /
s->values[s->size] = value;
s->size += 1;
}
@ -33,41 +34,27 @@ float pop_stack(struct stack* s) {
void print_stack(struct stack* s) {
for (int i = 0; i < s->size; i++) {
printf("%.2f ", s->values[i]);
printf("%.2f ", s->values[i]);
}
printf("\n");
printf("\n");
}
void process_operation(struct stack* s, const char* operation) {
float b = pop_stack(s);
float a = pop_stack(s);
if (strcmp(operation, "+") == 0) {
push_stack(s, a + b);
} else if (strcmp(operation, "-") == 0) {
push_stack(s, a - b);
} else if (strcmp(operation, "*") == 0) {
push_stack(s, a * b);
} else if (strcmp(operation, "/") == 0) {
if (b == 0) {
printf("Chyba: Delenie nulou.\n");
exit(1);
}
push_stack(s, a / b);
}
int is_number(const char* str) {
char* endptr;
strtof(str, &endptr);
return endptr != str && *endptr == '\0';
}
int main() {
struct stack mystack;
init_stack(&mystack);
init_stack(&mystack);
char input[256];
int has_input = 0;
char input[20];
printf("Poľská kalkulačka\n");
while (1) {
printf("Zadajte číslo alebo operáciu (+, -, *, /): ");
printf("Enter a number or an operation (+, -, *, /): ");
if (!fgets(input, sizeof(input), stdin)) {
break;
}
@ -75,36 +62,50 @@ int main() {
input[strcspn(input, "\n")] = 0;
char* endptr;
float value = strtof(input, &endptr);
if (endptr != input) {
if (is_number(input)) {
float value = strtof(input, NULL);
push_stack(&mystack, value);
has_input = 1;
print_stack(&mystack);
continue;
}
if (strcmp(input, "+") == 0 || strcmp(input, "-") == 0 ||
strcmp(input, "*") == 0 || strcmp(input, "/") == 0) {
if (mystack.size < 2) {
printf("Chyba: Nedostatok hodnôt v zásobníku.\n");
break;
}
process_operation(&mystack, input);
print_stack(&mystack);
} else {
printf("Chyba: Neplatný vstup.\n");
break;
}
}
if (mystack.size < 2) {
printf("Error: Not enough values on the stack to perform operation.\n");
break;
}
float b = pop_stack(&mystack);
float a = pop_stack(&mystack);
float result;
if (has_input) {
printf("no input\n");
} else {
printf("no input\n");
switch (input[0]) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b == 0) {
printf("Error: Division by zero.\n");
break;
}
result = a / b;
break;
default:
printf("Error: Unknown operation '%s'.\n", input);
push_stack(&mystack, a);
push_stack(&mystack, b);
break;
}
if (result) {
push_stack(&mystack, result);
print_stack(&mystack);
}
}
}
return 0;