CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2005
    Location
    Madrid (Spain)
    Posts
    511

    [RESOLVED] rand_s

    From MSDN: http://msdn.microsoft.com/en-us/libr...(v=vs.80).aspx

    Code:
    int main( void )
    {
        int             i;
        unsigned int    number;
        double          max = 100.0;
        errno_t         err;
    
        // Display 10 random integers in the range [ 1,10 ].
        for( i = 0; i < 10;i++ )
        {
            err = rand_s( &number );
            if (err != 0)
            {
                printf_s("The rand_s function failed!\n");
            }
            printf_s( "  %u\n", (unsigned int) ((double)number /
                              (double) UINT_MAX * 10.0) + 1);
        }
    
        printf_s("\n");
    
        // Display 10 random doubles between 0 and max.
        for (i = 0; i < 10;i++ )
        {
            err = rand_s( &number );
            if (err != 0)
            {
                printf_s("The rand_s function failed!\n");
            }
            printf_s( "  %g\n", (double) number / 
                              (double) UINT_MAX * max );
        }
    }

    But: what about if I want generate aleatory numbers between 123 and 256?? (for example).

    Thanks in advance.

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: rand_s

    Use the modulus operator to give you the range, then add the starting value to the generated number.

  3. #3
    Join Date
    Feb 2005
    Location
    Madrid (Spain)
    Posts
    511

    Re: rand_s

    Thanks.

    This is the code:

    Code:
    inline int Aleatorio(int nMin, int nMax) {	
    	UINT nNumero = 0;
    	rand_s(&nNumero);	
    	UINT n_s = nMin + nNumero % (nMax + 1 - nMin);
    	return n_s;
    }
    Best regards, Toño


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

Featured