Added division by zero detection

This commit is contained in:
Vera Lewis
2025-03-14 02:26:24 -05:00
parent d30d861c2b
commit 56edfa1fef
2 changed files with 15 additions and 2 deletions

View File

@@ -1,4 +1,4 @@
#include "ee.h" #include "ee.h"
int error = 0; int error = 0;
void printStack(STACK); void printStack(STACK);
@@ -75,6 +75,11 @@ arrity(const char query)
0; 0;
} }
bool
isDivByZero(double *_operands)
{
return _operands[0] == 0;
}
double double
evaluate(STACK* target_stack, char operator) evaluate(STACK* target_stack, char operator)
@@ -107,7 +112,10 @@ evaluate(STACK* target_stack, char operator)
break; break;
case '/' : case '/' :
value = _operands[1] / _operands[0]; if (isDivByZero(_operands))
error |= ERR_DIV_BY_ZERO;
else
value = _operands[1] / _operands[0];
break; break;
case '^' : case '^' :
@@ -187,6 +195,9 @@ report(STACK* expr, char* fmt)
else if (error & ERR_INVALID_FACTORIAL) else if (error & ERR_INVALID_FACTORIAL)
printf("Error: Factorials are only supported for positive integers.\n"); printf("Error: Factorials are only supported for positive integers.\n");
else if (error & ERR_DIV_BY_ZERO)
printf("Undefined\n");
else else
printf(fmt, peek(expr)); printf(fmt, peek(expr));
} }

View File

@@ -1,5 +1,6 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h>
#include <math.h> #include <math.h>
#include <ctype.h> #include <ctype.h>
#include <string.h> #include <string.h>
@@ -9,6 +10,7 @@ const int ERR_NS_OPERANDS = 1;
const int ERR_NS_OPERATORS = 2; const int ERR_NS_OPERATORS = 2;
const int ERR_INVALID_INPUT = 4; const int ERR_INVALID_INPUT = 4;
const int ERR_INVALID_FACTORIAL = 8; const int ERR_INVALID_FACTORIAL = 8;
const int ERR_DIV_BY_ZERO = 16;
struct EE_STACK_NODE { struct EE_STACK_NODE {