Added division by zero detection
This commit is contained in:
13
src/ee.c
13
src/ee.c
@@ -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,6 +112,9 @@ evaluate(STACK* target_stack, char operator)
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case '/' :
|
case '/' :
|
||||||
|
if (isDivByZero(_operands))
|
||||||
|
error |= ERR_DIV_BY_ZERO;
|
||||||
|
else
|
||||||
value = _operands[1] / _operands[0];
|
value = _operands[1] / _operands[0];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -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));
|
||||||
}
|
}
|
||||||
|
|||||||
2
src/ee.h
2
src/ee.h
@@ -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 {
|
||||||
|
|||||||
Reference in New Issue
Block a user