Floating Point Exception

Oct 23, 2011 at 9:13pm
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 :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
int GetNext(char s[]) {
    if(s[i] == '(') 		/* if parantheses are found */
	return '(';
    else if(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);
    }
    else if(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);
	}
	else if(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 :)
Last edited on Oct 23, 2011 at 9:16pm
Oct 23, 2011 at 9:56pm
I haven't looked at your code very closer, but it could be division by zero. You should check that.
Cheers.
Oct 23, 2011 at 10:00pm
Yeah I realized that. When I was looking up the problem I determined that at some point in MultiplyDivide I was dividing by zero.
Oct 24, 2011 at 9:41pm
bump, I'm stumped on this!
Oct 24, 2011 at 10:22pm
What is the expression you are feeding into this?

(Remember that integer division does not produce numbers with fractional parts.)
Oct 24, 2011 at 10:34pm
Any expression with parentheses! For example, the expression: (4 + 5) * 6 will cause a floating point exception.
Oct 24, 2011 at 11:10pm
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.
Topic archived. No new replies allowed.