Thread: Randomize Number Function

  1. #1
    Distributed Programming beyonddc's Avatar
    Join Date
    Dec 2001
    Location
    Mass
    Posts
    31

    Question Randomize Number Function

    Hi, I would need help on a randomize number function

    I included
    #include<ctime>

    and below is my randomize function (Noted that I am just randomize between 0 and 1).
    int randomVH()
    {
    int num;
    srand(time(0));
    num=(rand()%2);
    return num;
    }

    This is partial code in my main. (Noted that I am generating 100 numbers.)
    for(;counter<100;counter++)
    {
    num=randomVH();
    cout<<counter<<"\t"<<num<<endl;
    }

    With this code, somehow I am generating the same number inside this loop. I am hopping if anyone can fix my random function for me so I can generate number instead of same number inside the loop.

  2. #2
    Still A Registered User DISGUISED's Avatar
    Join Date
    Aug 2001
    Posts
    499
    You only want to seed the random function once, you are calling the srand function each time. Read the FAQ, FAQ Board or do a search for similar posts because this topic has been discussed many times. Hope that helps. Have a nice day.

  3. #3
    Registered User Twiggy's Avatar
    Join Date
    Oct 2001
    Posts
    43
    static int Count=0;

    if(Count==0)
    {
    Count++;
    srand(time(NULL));
    }
    computer_choice = rand()%2;

    That's what someone posted for me when I needed the help. Hope it helps ya out some.
    To error is human, to really foul things up requires a computer

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Just an 'FYI', 'static' members are initialized to zero by default, so you don't actually have to set them implicitly.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  3. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  4. help with a source code..
    By venom424 in forum C++ Programming
    Replies: 8
    Last Post: 05-21-2004, 12:42 PM
  5. Creating a student grade book-how?
    By Hopelessly confused in forum C Programming
    Replies: 5
    Last Post: 10-03-2002, 08:43 PM