Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>rand()</code> can be used to generate pseudo-random numbers in C++. In combination with <code>RAND_MAX</code> and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need <em>truly</em> random numbers with normal distribution, you'll need to employ a more advanced method.</p> <hr> <p>This will generate a number from 0.0 to 1.0, inclusive.</p> <pre><code>float r = static_cast &lt;float&gt; (rand()) / static_cast &lt;float&gt; (RAND_MAX); </code></pre> <p>This will generate a number from 0.0 to some arbitrary <code>float</code>, <code>X</code>:</p> <pre><code>float r2 = static_cast &lt;float&gt; (rand()) / (static_cast &lt;float&gt; (RAND_MAX/X)); </code></pre> <p>This will generate a number from some arbitrary <code>LO</code> to some arbitrary <code>HI</code>:</p> <pre><code>float r3 = LO + static_cast &lt;float&gt; (rand()) /( static_cast &lt;float&gt; (RAND_MAX/(HI-LO))); </code></pre> <hr> <p>Note that the <code>rand()</code> function will often not be sufficient if you need truly random numbers.</p> <hr> <p>Before calling <code>rand()</code>, you must first "seed" the random number generator by calling <code>srand()</code>. This should be done once during your program's run -- not once every time you call <code>rand()</code>. This is often done like this:</p> <pre><code>srand (static_cast &lt;unsigned&gt; (time(0))); </code></pre> <p>In order to call <code>rand</code> or <code>srand</code> you must <code>#include &lt;cstdlib&gt;</code>.</p> <p>In order to call <code>time</code>, you must <code>#include &lt;ctime&gt;</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload