Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top