Hey, can anyone tell me why I'm getting a floating point exception in the following C program? The program will run fine if I give it an expression without any parenthesis, but if there are parantheses I get a floating point exception in the function MultiplyDivide (sorry I couldn't think of a better name :/) Here's the relevant code, if you want me to post the rest I will :)
int GetNext(char s[]) {
if(s[i] == '(') /* if parantheses are found */
return'(';
elseif(s[i] == ')')
return')';
int sign = (s[i-1] == '-') ? -1 : 1; /* if the number is negative */
int digit = 0;
if(isdigit(s[i])) { /* grab the number */
while(isdigit(s[i])) {
digit = 10 * digit + (s[i] - '0');
++i;
}
}
if(s[i] == '*' || s[i] == '/')
return MultiplyDivide(s, digit, sign);
return digit * sign;
}
int MultiplyDivide(char s[], int digit, int sign) {
if(s[i] == '*') {
++i;
return GetNext(s) * (digit * sign);
}
elseif(s[i] == '/') {
++i;
return GetNext(s) / (digit * sign);
}
else /* if there was an error... */
PrintError(s, "MultiplyDivide");
}
int open = 0, close = 0; /* number of opening and closing parantheses */
int Parantheses(char s[]) {
++open;
int total = 0; /* total value of the parantheses */
while(open != close) {
int digit = GetNext(s);
if(digit == '(') { /* if there is an opening or closing paren */
++open;
++i;
total += Parantheses(s);
}
elseif(digit == ')') {
++close;
++i;
}
else {
total += digit;
++i;
}
}
return total;
}
Thanks :)
P.S. Feel free to rip on bad coding style and the likes as well :)
Hmm... What exactly is controlling the recursion here? For example, if s="(1)*1", it looks like GetNext(s) will call MultiplyDivide(s) at the end, which will call GetNext(s), and so on. No state about the parsing progress seems to be kept.