문제

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?

도움이 되었습니까?

해결책

In mathematics, x mod 0 is undefined, hence the error.

다른 팁

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.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top