c++除以 0
我正在运行长时间模拟。我将结果记录到向量中以计算有关数据的统计信息。我意识到,从理论上讲,这些样本可能是除以零的结果;这只是理论上的,我很确定事实并非如此。为了避免修改代码后重新运行模拟,我想知道这种情况下会发生什么。我能知道是否发生了除以 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于 IEEE 浮点数,有限非零浮点数除以 0 是明确定义的,并且结果为 +无穷大(如果值大于零)或 -无穷大(如果值小于零)。 0.0/0.0 的结果是 NaN。如果您使用整数,则行为未定义。
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.
请注意,C 标准说 (6.5.5):
因此,对于整型和浮点来说,something/0 都是未定义的(按照标准)。尽管如此,大多数实现都有前面提到的行为(+-INF 或 NAN)。
Note that C standard says (6.5.5):
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).
如果您正在谈论整数,那么您的程序应该在除以零时崩溃。
如果您谈论的是浮点数,则允许除以零,结果为 INF 或 -INF。现在,如果程序崩溃、妥善处理或继续出现未定义/意外的结果,则完全取决于您的代码。
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.
如果您使用 IEEE 浮点数,那么它将返回 0 或 NaN。如果 op1 为 0,您将得到未定义的结果。如果 op1 高于 0,您将得到无穷大。如果 op1 小于 0,那么您将得到 -Infinity。如果直接除以 0 或整数除以 0,则会出现“浮点异常”错误。
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".
结果=inf 是无穷大
result=inf is infinity