Modulo returns wrong result when using negatives

安稳与你 提交于 2019-12-11 03:23:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!