My Code:

long long difft, intrv ;

cout << "difft = " << difft << endl;
cout << "intrv = " << intrv << endl;
cout << "difft mod intrv = " << difft%intrv << endl;

Output:

 difft = 0
 intrv = 0
 difft mod intrv = 1

The result of 0%0 is zero, but in my code the result is "1", Why?

有帮助吗?

解决方案

In C++ the result of anything mod 0 is undefined behavior, from the draft C++ standard section 5.6 Multiplicative operators paragraph 4 says (emphasis mine):

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.[...]

Also, using uninitialized variables is also undefined behavior, so the behavior of this program is unpredictable.

其他提示

It is undefined behavior, because modulo involves a division by zero.

You cannot divide by 0! It's a compiler fault, that it let you do this. That's why you see 1.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top