문제

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