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
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)
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.
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.
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.
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.
#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;
}