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;
}
@ -39,35 +40,21 @@ void print_stack(struct stack* s) {
}
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);
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;
if (is_number(input)) {
char* endptr;
float value = strtof(input, &endptr);
if (endptr != input) {
float value = strtof(input, NULL);
push_stack(&mystack, value);
has_input = 1;
print_stack(&mystack);
continue;
}
} else {
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");
printf("Error: Not enough values on the stack to perform operation.\n");
break;
}
process_operation(&mystack, input);
float b = pop_stack(&mystack);
float a = pop_stack(&mystack);
float result;
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);
} else {
printf("Chyba: Neplatný vstup.\n");
break;
}
}
if (has_input) {
printf("no input\n");
} else {
printf("no input\n");
}
return 0;