c++ division by 0

2019-01-18 22:38发布

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

5条回答
闹够了就滚
2楼-- · 2019-01-18 23:01

If you use IEEE floats, then it will return 0 or NaN. If the op1 is 0, you will get undefined. If op1 is higher than 0, you will get Infinity. If op1 is lower than 0, then you will get -Infinity. If you use dividing by 0 directly or in integer , you will get error "Floating point exception".

查看更多
可以哭但决不认输i
3楼-- · 2019-01-18 23:09

Depends if you are using integers or floating points numbers. For integer, you'll get a runtime exception. For floating point numbers, the result will be +/- infinity, or NaN for (0.0/0.0), which you can test using std::isnan().

查看更多
一夜七次
4楼-- · 2019-01-18 23:18

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).

查看更多
何必那么认真
5楼-- · 2019-01-18 23:20

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.

查看更多
唯我独甜
6楼-- · 2019-01-18 23:22

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.

查看更多
登录 后发表回答