问题
I want to calculate: (-15 % 3) which should be 0 but instead i'm getting 1:
When i explicitly do:
int IntFcn (const void *key, size_t tableSize)
{
printf("%d\n",(*(int*)key)); // prints -15
printf("%d\n",tableSize); // prints 3
printf("%d\n",(-15) % 3); // prints 0
}
I get the right result (0) but when i try to use the variables below i get 1:
int IntFcn (const void *key, size_t tableSize)
{
printf("%d\n",(*(int*)key)); // prints -15
printf("%d\n",tableSize); // prints 3
printf("%d\n",((*(int*)key) % tableSize)); // prints 1
return ((*(int*)key) % tableSize);
}
Why is this happening?
回答1:
In your second case the second operand of modulo is unsigned integer thus the first operand is promoted to unsigned as well before performing the modulo. So the result will be (unsigned)(-15) % 3 which is equal (for 32-bit int) to 4294967281 % 3 == 1.
回答2:
try this..
return ((*(int*)key) % (int)tableSize);
来源:https://stackoverflow.com/questions/14039844/modulo-returns-wrong-result-when-using-negatives