|
|
|
#1
|
||||
|
||||
modulo operator?
ok how do you use this... I never learned this in math..ever.
I need to use it in programming to do something.. I have to take in 4 numbers into an array.. 4 "random" numbers between the values [0,5]... so I have to "mod" the random numbers I think that and I need to figure out why my array isnt taking in 4 values. " int i; int number; board[4]; srand(time(NULL)); for(i=0;i<4;i++) board[i]=0; for(i=0;i<5;i++) { board[number] = rand()%10; } " |
#2
|
||||
|
||||
A 12 hour clock uses Modulo-12 arithmetic. So 13 o'clock is 1 o'clock. 5=1 in Modulo-4 arithmetic.
__________________
You don't need a weatherman to know which way the wind blows - Robert A. Zimmerman |
#3
|
|||
|
|||
Yes, you can use rand()%6 to get a number in the range of [0,5].
For any purists out there, I will note that as this uses only the low bits of the result of rand(), it is not very random. You should be using the high bits by dividing by RAND_MAX in floating-point, multiply by 6, then convert to an integer. Also note that the modulus operator is well-defined on positive inputs only. That's not something to worry about with the return value of rand(). |
#4
|
||||
|
||||
Quote:
|
#5
|
|||
|
|||
Actually divide by RAND_MAX + 1.0. That way the quotient is less than one. Adding 1.0 rather than 1 promotes all values to double.
int random(int mod) { return (int)(mod * rand()/(RAND_MAX + 1.0)); } random(N) will return an integer in the range of [0,N-1]. |
#6
|
||||
|
||||
got it to generate 4 random numbers into the array
int i; board[4]; srand(time(NULL)); for(i=0;i<4;i++) board[i] = rand() %6 ; now I need to do 7 more functions.. I think those functions need to call board[4] to compare against.. |
Bookmarks |
|
|