Thread: Seeding Random Number Generator

  1. #1
    Registered User zdude's Avatar
    Join Date
    Sep 2002
    Posts
    32

    Seeding Random Number Generator

    Could someone show me some good ways to seed the random number generator in both C and C++?
    Those who live by the sword get shot by those who don't.

    I can C.

    Compiler: gcc

  2. #2
    Registered User zdude's Avatar
    Join Date
    Sep 2002
    Posts
    32
    I wanted to know how to do it in C++ too, randomize does not work in C++. (For me at least)
    Those who live by the sword get shot by those who don't.

    I can C.

    Compiler: gcc

  3. #3
    Still A Registered User DISGUISED's Avatar
    Join Date
    Aug 2001
    Posts
    499
    Did you read the whole thing?

    Straight from the FAQ
    That said: There is more than one way to initialize the random seed (other than randomize). Randomize will not work under all compilers. And since the seed must be initialized (or the numbers will not be random) here is the other way:

    #include <stdlib.h> //for rand

    #include <stdio.h> //for printf

    #include <time.h> //for time



    int main(void)

    {

    srand(time(NULL));

    printf("A random number from 0 to 99: %d", rand() % 100);

    return 0;

    }


    srand initilizes the seed based on the number inputed. Normally time() is used so that the number is different each time the program is run. If you use srand(x); (where x is equal to any constant number) you will recieve random numbers but they will be the same on each execution.

    Q: But, how do i get a number between x and y? Like a die or something?
    A: Use a function like this one...



    int rand_mid(int low, int high)

    {

    return low+rand()%(high-low+1);

    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Random Number Generator Class
    By abachler in forum Windows Programming
    Replies: 4
    Last Post: 09-03-2008, 08:30 AM
  2. Random number generator
    By rehan in forum C++ Programming
    Replies: 1
    Last Post: 02-25-2008, 02:14 AM
  3. Issue w/ Guess My Number Program
    By mkylman in forum C++ Programming
    Replies: 5
    Last Post: 08-23-2007, 01:31 AM
  4. Good Random Number Generator
    By MethodMan in forum C Programming
    Replies: 4
    Last Post: 11-18-2004, 06:38 AM
  5. how to link random number generator with cpu?
    By chris285 in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2003, 05:26 AM