What do you do to prevent 1/0?

Sep 18, 2008 at 12:24pm
Hi guys. Just a general question, what do you guys normally do to prevent 1/0? I am writting a calculator program, and it crashes everytime someone enter 1/0. I understand why but don't know what I should do about it. Should I just make it so everytimes someone enter 1/0. It return 0. Or just use exception? I would like some input on what you guys normally do to prevent 1/0 in your program. O.o
Sep 18, 2008 at 12:39pm
You mean the division with 0?
Then just add a condition to check the divider if it is 0 and prompt the user that the result is infinite (or undefined, depends on the math you know)
Last edited on Sep 18, 2008 at 1:42pm
Sep 18, 2008 at 1:04pm
Well it definitely shouldn't return 0, that's completely wrong mathematically. I usually put undefined for that calculation unless I'm dealing with some form of approximation or physical representations.
Sep 18, 2008 at 1:27pm
I follow the law of undefined behavior and apply it to mathematics, making demons fly out of the user's nose. Serves him right for giving me wrong data.
Alternatively, if I'm doing some sort of parsing I make it so that the function returns an error code and write the actual value to the variable pointed to by some parameter.
Sep 18, 2008 at 10:42pm
X/0 = the dog said hello it's. :). I didn't even know you have to look out for thing like that until I trieded it, and my pc when frozen and crashes. lolz. Thank you guys.
Sep 18, 2008 at 10:52pm
O_o
The operating system crashed from a SIGFPE?
Sep 18, 2008 at 11:48pm
Yes. 1/0. Frozen solid. Crashes. I don't know. Window XP. lolz. ^_^
Sep 18, 2008 at 11:51pm
You might want to get youself a pretty aggressive antivirus and have it scan everything you've got.

Anything that is modifying the OS's response to faults is not your friend.
Sep 19, 2008 at 2:25am
In my openion, check the divisor is zero or less and throw an exception. I would do the same, throw an exception from the class and dont let it go any further.

Any program should not crash when an error occurs otherwise it be a badly designed program.

Check it out. Good luck :)


Sep 21, 2008 at 7:57pm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define ZERO 1e-10
#define isZero(A) ( (A < ZERO) && (A > -ZERO) )

int main() {

 double x = 0.0;

 if (isZero(x)) 
  cout << "x is zero" << endl;
 else
  cout << "x is not zero" << endl;

 return 0;
}


Last edited on Sep 21, 2008 at 7:58pm
Topic archived. No new replies allowed.