C : Modulus operator on unsigned int gives unexpected output

旧城冷巷雨未停 提交于 2019-11-30 09:12:03

问题


#include <stdio.h>

main() {
    unsigned a = -20;
    unsigned b = 10;
    printf("%d\n", (a % b));
    printf("%d\n", (-20 % 10));
}

Output:
6
0

The second printf prints the expected value of 0 while the first printf prints 6. Why this unexpected output with unsigned ints?


回答1:


unsigned int can hold values from 0 to UINT_MAX, no negative values. So -20 is converted to -20 + UINT_MAX + 1.

On your system:

(-20 + UINT_MAX + 1) % 10 != -20 % 10



回答2:


And what are you expecting?

a % b is equivalent to, let's substitute the values and apply the unary - to the unsigned int value of 20, (UINT_MAX-20+1) % 10 and the type of the result is unsigned int and you're printing it with %d, which is wrong. You should use %u here.



来源:https://stackoverflow.com/questions/16122213/c-modulus-operator-on-unsigned-int-gives-unexpected-output

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