Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ division by 0

I am running long simulations. I record the results into a vector to compute statistics about the data. I realized that, in theory, those samples could be the result of a division by zero; this is only theoretical, I am pretty sure it's not the case. In order to avoid rerunning the simulation after modifying the code, I was wondering what happens in that case. Would I be able to realize whether a division by 0 has occurred or not? Will I get error messages? (Exceptions are not being handled at the moment).

Thanks

like image 938
Bob Avatar asked Jan 20 '11 09:01

Bob


People also ask

What happens if you divide by zero in C?

Because what happens is that if we can say that zero, 5, or basically any number, then that means that that "c" is not unique. So, in this scenario the first part doesn't work. So, that means that this is going to be undefined. So zero divided by zero is undefined.

What type of error is division by zero in C?

Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations. If you write a code without using exception handling then the output of division by zero will be shown as infinity which cannot be further processed.

Can you force a computer to divide by zero?

Division by zero is a definite no-no whenever you're doing math. It simply doesn't make any sense from an arithmetic standpoint as there is no possible number which can output the numerator when multiplied by zero. So, when something is divided by zero, mathematicians simply state that the answer is 'undefined'.


3 Answers

For IEEE floats, division of a finite nonzero float by 0 is well-defined and results in +infinity (if the value was >zero) or -infinity (if the value was less than zero). The result of 0.0/0.0 is NaN. If you use integers, the behaviour is undefined.

like image 70
etarion Avatar answered Oct 10 '22 16:10

etarion


Note that C standard says (6.5.5):

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

So something/0 is undefined (by the standard) both for integral types and Floating points. Nevertheless most implementations have fore mentioned behavior (+-INF or NAN).

like image 37
Огњен Шобајић Avatar answered Oct 10 '22 17:10

Огњен Шобајић


If you're talking integers then your program should crash upon division by zero.

If you're talking floats then division by zero is allowed and the result to that is INF or -INF. Now it's all up to your code if the program will crash, handle that nicely or continue with undefined/unexpected results.

like image 40
Shinnok Avatar answered Oct 10 '22 18:10

Shinnok