From 56edfa1fef0e4643b3256240c8b788b657428a9f Mon Sep 17 00:00:00 2001 From: Vera Lewis Date: Fri, 14 Mar 2025 02:26:24 -0500 Subject: [PATCH] Added division by zero detection --- src/ee.c | 15 +++++++++++++-- src/ee.h | 2 ++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/ee.c b/src/ee.c index e47b9dc..a6b790c 100644 --- a/src/ee.c +++ b/src/ee.c @@ -1,4 +1,4 @@ - #include "ee.h" +#include "ee.h" int error = 0; void printStack(STACK); @@ -75,6 +75,11 @@ arrity(const char query) 0; } +bool +isDivByZero(double *_operands) +{ + return _operands[0] == 0; +} double evaluate(STACK* target_stack, char operator) @@ -107,7 +112,10 @@ evaluate(STACK* target_stack, char operator) break; case '/' : - value = _operands[1] / _operands[0]; + if (isDivByZero(_operands)) + error |= ERR_DIV_BY_ZERO; + else + value = _operands[1] / _operands[0]; break; case '^' : @@ -187,6 +195,9 @@ report(STACK* expr, char* fmt) else if (error & ERR_INVALID_FACTORIAL) printf("Error: Factorials are only supported for positive integers.\n"); + else if (error & ERR_DIV_BY_ZERO) + printf("Undefined\n"); + else printf(fmt, peek(expr)); } diff --git a/src/ee.h b/src/ee.h index cd4c4d0..77faa9b 100644 --- a/src/ee.h +++ b/src/ee.h @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -9,6 +10,7 @@ const int ERR_NS_OPERANDS = 1; const int ERR_NS_OPERATORS = 2; const int ERR_INVALID_INPUT = 4; const int ERR_INVALID_FACTORIAL = 8; +const int ERR_DIV_BY_ZERO = 16; struct EE_STACK_NODE {