Thread: Prelude's random numbers tutorial

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    FOX
    Join Date
    May 2005
    Posts
    188

    Prelude's random numbers tutorial

    Why does this code from her tutorial only print out negative numbers? I thought it was supposed to print out numbers between 1-10.
    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    int main()
    {
      std::srand ( (unsigned int)std::time ( 0 ) );
      std::cout<< (int)( (double)std::rand() / ( RAND_MAX + 1 ) * 10 ) <<std::endl;
    
      return 0;
    }
    I don't understand how (double)std::rand() / ( RAND_MAX + 1 ) could ever be a negative number, unless rand() is generating one (which would seem a tad odd). Or maybe it's (RAND_MAX + 1) that is somehow overflowing to -RAND_MAX?

    EDIT: It is indeed (RAND_MAX+1) that is overflowing.
    Last edited by ^xor; 06-10-2005 at 07:57 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. questions....so many questions about random numbers....
    By face_master in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2009, 08:47 AM
  2. Generatin Random Numbers
    By dantu1985 in forum C Programming
    Replies: 15
    Last Post: 08-13-2007, 01:21 AM
  3. Generating 100k to 1 million unique random numbers
    By Ariod in forum C Programming
    Replies: 4
    Last Post: 08-26-2005, 12:59 PM
  4. random number tutorial
    By 7stud in forum C++ Programming
    Replies: 3
    Last Post: 07-26-2005, 02:41 PM
  5. Random numbers (about the tutorial)
    By face_master in forum C++ Programming
    Replies: 3
    Last Post: 08-26-2001, 06:56 AM