POV-Ray : Newsgroups : povray.off-topic : My first C++ program : Re: A test Server Time
1 Oct 2024 09:23:26 EDT (-0400)
  Re: A test  
From: Warp
Date: 20 Sep 2008 19:35:55
Message: <48d588db@news.povray.org>
Orchid XP v8 <voi### [at] devnull> wrote:
> Because for starters, the first thing I'm gonna want to know is how to
> choose a random number in C++. ;-)

  C++ itself doesn't have a random number library (something which will
be fixed in the next C++ standard), but <cstdlib> does have a rand()
function. Rather unusually for a C function, the usage of rand() is
simple and safe: You simply call it, and it returns a random integer
value between 0 and RAND_MAX.

  A simple way of getting a value so that 0 <= value < n, is:

    int value = std::rand() % n;

  Of course it will always return the same values every time you run the
program. If you want it to return different values, you'll have to seed
it with a clock value. Again, no time functions in C++, but the C versions
are also unusually easy and safe to use (at least in this case). Include
<ctime> and then you can seed the rng at the beginning of your program:

    std::srand(std::time(0));

  And by the way, no, this will probably not work correctly:

    int value = std::rand() * n / RAND_MAX;

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.