signedness

signed int modulo unsigned int produces nonsense results

喜你入骨 提交于 2020-06-15 20:31:15
问题 I need to perform a real mathematical modulo in C. It makes sense for me to allow negative numbers for the moduled argument, since my modular calculations can produce negative intermediate results, which must be put back into the least residue system. But it makes no sense to allow negative module, therefore i wrote unsigned int mod( int x, unsigned int m ) { int r = x % m; return r >= 0 ? r : r + m; } However calling such function with negative number and positive module printf("%u\n", mod(

signed int modulo unsigned int produces nonsense results

别说谁变了你拦得住时间么 提交于 2020-06-15 20:28:46
问题 I need to perform a real mathematical modulo in C. It makes sense for me to allow negative numbers for the moduled argument, since my modular calculations can produce negative intermediate results, which must be put back into the least residue system. But it makes no sense to allow negative module, therefore i wrote unsigned int mod( int x, unsigned int m ) { int r = x % m; return r >= 0 ? r : r + m; } However calling such function with negative number and positive module printf("%u\n", mod(