C : Modulus operator on unsigned int gives unexpected output

前端 未结 2 879
天命终不由人
天命终不由人 2020-12-20 11:26
#include 

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

Output:
6
0
         


        
2条回答
  •  礼貌的吻别
    2020-12-20 12:07

    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.

提交回复
热议问题