Update cv3/program.c

This commit is contained in:
Marat Izmailov 2024-10-17 12:19:39 +00:00
parent 45b15ad033
commit 768000285e

View File

@ -1,116 +1,81 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define STACK_SIZE 10
double stack[STACK_SIZE];
int top = 0;
struct stack {
float values[STACK_SIZE];
int size;
};
void init_stack(struct stack* s) {
memset(s, 0, sizeof(struct stack));
}
void push_stack(struct stack* s, float value) {
assert(s->size < STACK_SIZE);
s->values[s->size] = value;
s->size += 1;
}
float pop_stack(struct stack* s) {
assert(s->size > 0);
s->size -= 1;
return s->values[s->size];
}
void print_stack(struct stack* s) {
for (int i = 0; i < s->size; i++) {
printf("%.2f ", s->values[i]);
void print_stack() {
for (int i = 0; i < top; i++) {
printf("%.2f ", stack[i]);
}
printf("\n");
}
int is_number(const char* str) {
char* endptr;
strtof(str, &endptr);
return endptr != str && *endptr == '\0';
int push(double value) {
if (top >= STACK_SIZE) {
printf("full stack\n");
return 0;
}
stack[top++] = value;
print_stack();
return 1;
}
int main() {
struct stack mystack;
init_stack(&mystack);
char input[20];
while (1) {
printf("Enter a number or an operation (+, -, *, /): ");
if (!fgets(input, sizeof(input), stdin)) {
break;
int pop(double *value) {
if (top <= 0) {
printf("not enough operands\n");
return 0;
}
*value = stack[--top];
return 1;
}
int apply_operation(char op) {
double a, b;
input[strcspn(input, "\n")] = 0;
if (is_number(input)) {
float value = strtof(input, NULL);
push_stack(&mystack, value);
print_stack(&mystack);
} else {
if (mystack.size < 2) {
printf("Error: Not enough values on the stack to perform operation.\n");
break;
if (!pop(&b) || !pop(&a)) {
return 0;
}
float b = pop_stack(&mystack);
float a = pop_stack(&mystack);
float result = 0;
switch (input[0]) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
double result;
switch (op) {
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");
push_stack(&mystack, a);
push_stack(&mystack, b);
print_stack(&mystack);
continue;
printf("division by zero\n");
return 0;
}
result = a / b;
break;
default:
printf("Error: Unknown operation '%s'.\n", input);
push_stack(&mystack, a);
push_stack(&mystack, b);
print_stack(&mystack);
continue;
}
push_stack(&mystack, result);
print_stack(&mystack);
}
}
printf("bad input\n");
return 0;
}
return push(result);
}
int main() {
char input[100];
while (scanf("%s", input) == 1) {
char *end;
double value = strtod(input, &end);
if (*end == '\0') {
if (!push(value)) return 0;
} else if (input[1] == '\0' && strchr("+-*/", input[0])) {
if (!apply_operation(input[0])) return 0;
} else {
printf("bad input\n");
return 0;
}
}
printf("no input\n");
return 0;
}