Random numbers
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Random numbers

Hybrid View

  1. #1
    Join Date
    Jan 2004
    Location
    Punjab, India
    Posts
    113

    Random numbers

    hi!
    I am using the following code to generate a random string. But each time i get the same string output. Can anyone help.

    char myarray[22];
    char* CGeneratorApp::GenerateString()
    {
    myarray[21]='\0';
    for(int k=0;k<21;k++)
    {
    myarray[k] = (char)(((int)rand()%25)+65);
    }

    char first[2];
    intUsed++;

    sprintf(first,"%d",intUsed);

    if(intUsed<10)
    {
    first[1]=first[0];
    first[0]='0';
    }

    first[0]=(char)((int)first[0]+27);
    first[1]=(char)((int)first[1]+27);

    myarray[8]=first[0];
    myarray[10]=first[1];

    AfxMessageBox(myarray);

    return myarray;
    }

    Thnx in advance

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    You need to initialize the random seed using srand() before calling rand(). e.g. srand(clock());

  3. #3
    Join Date
    Jun 2002
    Location
    Germany
    Posts
    1,557
    Here is a related post which offers additional, useful information.

    Sincerely, Chris.



    http://www.codeguru.com/forum/showth...hreadid=281630
    You're gonna go blind staring into that box all day.

  4. #4
    Join Date
    Jan 2004
    Location
    Punjab, India
    Posts
    113

    Thnx Everybody

    Thnx Everybody,
    U were of quite good help.

  5. #5
    Join Date
    Dec 2001
    Location
    Greece, Athens
    Posts
    1,015
    Originally posted by Kheun
    You need to initialize the random seed using srand() before calling rand(). e.g. srand(clock());
    Indeed, you need to call srand(), but not using clock(), because clock() will (possibly) return the same number, so the random seed will be initialized in the same way. A better way is to call srand like this:
    Code:
    srand( (unsigned)time( NULL ) );
    Theodore
    Personal Web Page (some audio segmentation tools): www.di.uoa.gr/~tyiannak

  6. #6
    Join Date
    Jun 2002
    Location
    Germany
    Posts
    1,557
    Indeed,

    Some developers even seed rand using some sort of a high-frequency ticker in the system, for example the time-stamp-counter in Pentium systems.

    I think that this is described in some other posts such as the link in my other response above.

    Sincerely, Chris.

    You're gonna go blind staring into that box all day.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center