问题
If I type:
int main() { return 0 % 0; }
I get back an error:
error C2124: divide or mod by zero
What is the reason behind this? Isn't the answer zero?
回答1:
In mathematics, x mod 0
is undefined, hence the error.
回答2:
From C++ standard, section 5.5:
If during the evaluation of an expression the result is not mathematically defined or not in the range of representable mathematical values for its type, the behavior is undefined. [...] Treatment of division by zero, forming a remainder using a zero divider, and all floating point exceptions vary among machines, and is usually adjustable by a library function.
Since remainder of a division by zero is mathematically undefined regardless of the number being divided, the answer is undefined according to the C++ standard.
回答3:
The mod function is effectively the same as the integer division function, except that it gives you the remainder, rather than the quotient. You can't divide by zero...
(BTW, as an aside, 0/0 is not even infinity, it's indeterminate.)
来源:https://stackoverflow.com/questions/19371340/why-is-0-mod-0-an-error