Results 1 to 3 of 3

Thread: ansi C: generate random integers

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Nov 2001
    Posts
    117

    Post ansi C: generate random integers

    Can anyone show me how to generate a set of random numbers, say a set of 10 integers?
    Thanx

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    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

  3. #3
    Addicted Member kikelinus's Avatar
    Join Date
    Nov 2000
    Posts
    219
    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
  •  



Click Here to Expand Forum to Full Width