Created
October 1, 2014 14:36
-
-
Save zeroeth/8749721982770efbe78b to your computer and use it in GitHub Desktop.
C modulus operator for negative numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <assert.h> | |
| int modulo(int dividend, int divisor) | |
| { | |
| int remainder = dividend % divisor; | |
| if(remainder < 0) { | |
| return remainder + divisor; | |
| } | |
| return remainder; | |
| } | |
| void test_non_symmetric_cycle() | |
| { | |
| printf("test: \"numbers are non symmetric about 0\"\n"); | |
| assert( modulo( 10, 3) == 1 ); | |
| assert( modulo( 7, 3) == 1 ); | |
| assert( modulo( 4, 3) == 1 ); | |
| assert( modulo( 3, 3) == 0 ); | |
| assert( modulo( 2, 3) == 2 ); | |
| assert( modulo( 1, 3) == 1 ); | |
| assert( modulo( 0, 3) == 0 ); | |
| assert( modulo( -1, 3) == 2 ); | |
| assert( modulo( -2, 3) == 1 ); | |
| assert( modulo( -3, 3) == 0 ); | |
| assert( modulo( -4, 3) == 2 ); | |
| assert( modulo( -7, 3) == 2 ); | |
| assert( modulo(-10, 3) == 2 ); | |
| } | |
| int main(int argc, char **argv) | |
| { | |
| test_non_symmetric_cycle ( ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment