1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Mod of Negative Numbers

Discussion in 'C' started by Venny, Jan 28, 2011.

  1. Venny

    Venny New Member

    Joined:
    Jan 26, 2011
    Messages:
    16
    Likes Received:
    0
    Trophy Points:
    0
    Hi All,

    This may not b a new question to most of you but since am a newbie, please consider answering this.

    For languages like c/c++ and java, how does mod % operator work with negative numbers.

    for e.g and trying to fetch the output of -3%2 . The actual output is -1 whereas it should be just one.

    Could you help me to come out with a solution on how shall I generate the correct output for negative numbers.

    thanks​
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Looks like it's not as simple as that: http://en.wikipedia.org/wiki/Modulo_operation

    Visual C++ 2008 test code:
    Code:
    void test39()
    {
    	for (int i=5; i>=-5; i--)
    	{
    		for (int j=-5; j<=5; j++)
    		{
    			if (j) printf("%4d",i%j); fflush(stdout);
    		}
    		printf("\n"); fflush(stdout);
    	}
    }
    
    Output:
    Code:
       0   1   2   1   0   0   1   2   1   0
       4   0   1   0   0   0   0   1   0   4
       3   3   0   1   0   0   1   0   3   3
       2   2   2   0   0   0   0   2   2   2
       1   1   1   1   0   0   1   1   1   1
       0   0   0   0   0   0   0   0   0   0
      -1  -1  -1  -1   0   0  -1  -1  -1  -1
      -2  -2  -2   0   0   0   0  -2  -2  -2
      -3  -3   0  -1   0   0  -1   0  -3  -3
      -4   0  -1   0   0   0   0  -1   0  -4
       0  -1  -2  -1   0   0  -1  -2  -1   0
    
    This seems correct to me. -3 % 2 calculates the remainder after the division -3 / 2. There are -1 2's in -3 so -3 / 2 = -1. After subtracting -1*2 from -3 you're left with -1.

    If you think it should be 1, does that mean you think the division should return -2? If you subtract X from -3 to get +1 then X has to be -4, i.e. -2*2.
     

Share This Page