modulo

Can I rely on % (modulo) operator in C for negative numbers?

元气小坏坏 提交于 2020-07-10 03:15:47
问题 Using GCC: printf("%i \n", -1 % (int)4); printf("%u \n", -1 % (unsigned int)4); Output: -1 3 Can I rely on this behaviour across platforms? Should I explicitly define MOD and REM macros to be sure this isn't altered? 回答1: From C99 onwards the result of % is required to be rounded toward 0 as quoted by Chris Dodd. Prior to C99 standard, % operator's behavior on negative number is implementation defined . When integers are divided and the division is inexact, if both operands are positive the

Can I rely on % (modulo) operator in C for negative numbers?

限于喜欢 提交于 2020-07-10 03:14:53
问题 Using GCC: printf("%i \n", -1 % (int)4); printf("%u \n", -1 % (unsigned int)4); Output: -1 3 Can I rely on this behaviour across platforms? Should I explicitly define MOD and REM macros to be sure this isn't altered? 回答1: From C99 onwards the result of % is required to be rounded toward 0 as quoted by Chris Dodd. Prior to C99 standard, % operator's behavior on negative number is implementation defined . When integers are divided and the division is inexact, if both operands are positive the

Python for loop with modulo

懵懂的女人 提交于 2020-06-26 07:15:12
问题 Is it possible to create a python for-loop with a modulo operation? I have a ringbuffer in Python and I want to iterate the elements between the startPos and endPos indexes, where startPos can have a bigger value than endPos . In other programming languages, I would intuitively implement this with a modulo operator: int startPos = 6; int endPos = 2; int ringBufferSize = 8; for(int i = startPos, i != endPos, i = (i+1) % ringBufferSize) { print buffer.getElementAt(i); } Is there a way to do

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(