|
|
1.1 ! root 1: ! 2: ! 3: modulus Definition modulus ! 4: ! 5: ! 6: ! 7: ! 8: Modulus is the operation that returns the remainder of a division ! 9: operation. For example, 12 modulus four equals zero, because ! 10: when 12 is divided by four it leaves no remainder. The term ! 11: ``modulo'' also refers to the product of a modulus operation; in ! 12: the above example, the modulo is zero. In C, the modulus opera- ! 13: tion is indicated with a percent sign `%'; therefore, 12 modulus ! 14: 4 is written 1122%44. ! 15: ! 16: The modulus operation often is used to trim numbers to a preset ! 17: range. For example, if you wanted to create a list of single- ! 18: digit random numbers, you would use the command: ! 19: ! 20: ! 21: rand()%10 ! 22: ! 23: ! 24: This is demonstrated by the following example. ! 25: ! 26: ***** Example ***** ! 27: ! 28: This example prints a list of 20 single-digit random numbers. ! 29: The random-number table is seeded with a portion of the current ! 30: system time. ! 31: ! 32: ! 33: main() ! 34: { ! 35: long nowhere; /* place to put unused data */ ! 36: int counter; ! 37: ! 38: ! 39: ! 40: srand((int)time(&nowhere)); ! 41: for (counter = 0; counter <20; counter++) ! 42: printf("%d\n", rand()%10); ! 43: } ! 44: ! 45: ! 46: ***** See Also ***** ! 47: ! 48: definitions, operator ! 49: ! 50: ***** Notes ***** ! 51: ! 52: The implementation of C defines how a modulus operator behaves ! 53: when it operates upon numbers with different signs. On the ! 54: i8086, ! 55: ! 56: ! 57: 10 % -4 ! 58: ! 59: ! 60: yields -2. This is not mathematical modulus, which is +2. ! 61: ! 62: ! 63: ! 64: COHERENT Lexicon Page 1 ! 65: ! 66:
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.