usaa24/cv3/program.c

127 lines
3.0 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STACK_SIZE 10
struct stack {
float values[STACK_SIZE];
int size;
};
void init(struct stack *s) {
s->size = 0;
}
void push_stack(struct stack *s, float value) {
if (s->size < STACK_SIZE) {
s->values[s->size] = value;
s->size++;
} else {
printf("no input.\n");
exit(1); // Exit the program on overflow
}
}
float pop_stack(struct stack *s) {
if (s->size > 0) {
s->size--;
return s->values[s->size];
} else {
printf("no input\n");
exit(1); // Exit the program on underflow
}
}
void print_stack(struct stack *s) {
if (s->size > 0) {
for (int i = 0; i < s->size; i++) {
printf("%.2f ", s->values[i]);
}
printf("\n");
}
}
int read(struct stack *s) {
char temp[100];
// Read a line of input
if (fgets(temp, sizeof(temp), stdin) == NULL) {
return 0; // Error reading input
}
// Check for empty input
if (strcmp(temp, "\n") == 0) {
printf("no input\n");
exit(1); // Exit on empty input
}
// Check for termination input
if (strcmp(temp, "end\n") == 0) {
return 0;
}
float value;
int scan = sscanf(temp, "%f", &value);
// If it's a number
if (scan == 1) {
push_stack(s, value);
print_stack(s); // Print the stack after adding
} else {
// If it's an operator
switch (temp[0]) {
case '+':
case '-':
case '*':
case '/': {
// Check for sufficient values in the stack
if (s->size < 2) {
printf("no input\n");
return 1; // Don't exit; continue to next iteration
}
float b = pop_stack(s); // Pop the last two values
float a = pop_stack(s);
float result;
switch (temp[0]) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/':
if (b == 0) {
printf("division by zero\n");
exit(0); // Exit on division by zero
}
result = a / b;
break;
}
push_stack(s, result); // Push the result back onto the stack
print_stack(s); // Print the stack after operation
printf("no input\n"); // Print the "no input" message
exit(0); // Exit the program after the operation
break;
}
default:
printf("no input\n");
exit(1); // Exit on invalid input
}
}
return 1; // Continue the loop
}
int main() {
struct stack my_stack;
init(&my_stack);
while (1) {
if (read(&my_stack) == 0) {
break;
}
}
return 0;
}