Search code examples
cdiscrete-mathematicsmodular-arithmetic

How c calculates remainder?


I have strange behaviour in one of my functions. Code of program is very huge and hardly readable. So i attaches part of functions. If j lower than 4, it returns not actual remainder, but difference between j and 4.

I tested and found, that 3 % 4 == 1 instead of 3.

while (j < 16)
{
    if ((crd + (j % 4)) + d * (j / 4) > d * d && str2[j] == 1)
        str[0] = 2;
    if (((crd + (j % 4) + d * (j / 4)) / d) - i != (j / 4) && str2[j] == 1)
        str[0] = 2;
    if (str2[j] == 1)
        str[(crd + (j % 4)) + d * (j / 4)] = str2[16];
    if (str[(crd + (j % 4)) + d * (j / 4)] == 2 || str[0] == 2)
        return (str);
    j++;
}

The question is how % operator works. screenshot of debugger


Solution

  • the following proposed code:

    1. cleanly compiles
    2. shows that the modulo operator works as expected

    and now, the proposed code:

    #include <stdio.h>
    
    int main( void )
    {
        int a = 3 % 4;
        printf( "%d\n", a );
    }
    

    when compiled/linked and run the result is:

    3
    

    above shows that the modulo operator works as expected.

    That leaves your code, which is not a [mcve] so the resulting probability is that something is wrong with your code. But we really cannot tell for sure as we don't have your code,