|
-
Apr 13th, 2002, 07:13 AM
#1
Thread Starter
Lively Member
ansi C: generate random integers
Can anyone show me how to generate a set of random numbers, say a set of 10 integers?
Thanx
-
Apr 13th, 2002, 08:11 AM
#2
Monday Morning Lunatic
Use the rand function from math.h
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Apr 14th, 2002, 06:36 PM
#3
Addicted Member
Code:
#include <stdio.h>
#include <stdlib.h> /* used to get the time*/
#include <math.h> /* random functions */
int main()
{
int i, random_number;
/* For it to be a true random number generator, you need a */
/* seed value, so we use the current time (given in seconds */
/* to change the seed value */
srand(time(NULL));
for(i=1; i<=10; i++) {
random_number = 1 + rand() % 10
printf("Number: %d\n", random_number);
}
return 0;
}
Here, we use a formula to generate a number between 1 and 10: "1 + rand() % 10"....
the formula is actually a + rand() %b
a being the first number (where to begin), and b being the last number.
Hope this helps.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|