Remainder after division by zero

你。 提交于 2021-02-05 07:36:18

问题


I know that division by zero is not allowed in math, but can I use modulo by zero and what answer should I get?

For example

10%0 = ?
5%0 = ?

回答1:


The standard defines it as "undefined".

In nearly all processors, the modulo is performed by the same functionality as divide. In modern larger processors, it's an instruction (x86 for example). Most often, this instruction will cause a trap when dividing by zero, and this applies whether the code is "intending to use the modulo" or "quotient" part.

It is undefined so that processors and compilers have the freedom to implement what they fancy - e.g. if the processor just returns whatever came in as the input, that's also allowed, or if it causes the entire OS to crash, that's "fine" too by the standard.

In summary, modulo of zero is just as bad as divide by zero.

(Note that typically, floating point divide by zero does NOT trap [by default], and produces a infinity value, except if the value divided is also zero, in which case you get "not a number")




回答2:


In C/C++ it is Undefined behaviour, you can get various of results depending on compiler or even different instances of same program.

C11dr §6.5.5

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined




回答3:


The result is UB

C11dr §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."




回答4:


Mathematically speaking you should get infinite, which is the correct answer... programmatically any sane compiler will warn you of division by zero as internally the modulo operator (at least in C/C++) is translated in a division (in most implementations). So the answer to your question is that you would get a floating point exception, in both cases.



来源:https://stackoverflow.com/questions/22275684/remainder-after-division-by-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!