Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You must seed the random number generator. <a href="http://www.cplusplus.com/reference/cstdlib/srand/" rel="noreferrer">see here for an example</a>.</p> <h1>not-seeded.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main () { printf ("Random not seeded: %d\n", rand()%10); return 0; } </code></pre> <h1>not-seeded output</h1> <pre><code>Random not seeded: 3 Random not seeded: 3 Random not seeded: 3 Random not seeded: 3 Random not seeded: 3 </code></pre> <h1>seeded.c</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int main () { srand(time(NULL)); printf ("Random seeded: %d\n", rand()%10); return 0; } </code></pre> <h1>seeded output</h1> <pre><code>Random fast seeded: 7 Random fast seeded: 7 Random fast seeded: 7 Random fast seeded: 1 Random fast seeded: 1 Random fast seeded: 1 Random fast seeded: 5 Random fast seeded: 5 Random fast seeded: 5 Random fast seeded: 5 </code></pre> <h1>fast-seeded.c</h1> <p>If you want to be able to call your utility more than once a second, you will have to use a different source for you seed, otherwise you will still end up with some repeated random numbers.</p> <p>Here is an example that uses nanoseconds instead of <code>time()</code> which only returns seconds.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int main () { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &amp;ts); /* using nano-seconds instead of seconds */ srand((time_t)ts.tv_nsec); printf ("Random fast seeded: %d\n", rand()%10); return 0; } </code></pre> <h1>fast-seeded output</h1> <p>You can see here that the numbers aren't grouped as much as the previous example.</p> <pre><code>Random fast seeded: 9 Random fast seeded: 6 Random fast seeded: 5 Random fast seeded: 6 Random fast seeded: 1 Random fast seeded: 1 Random fast seeded: 9 Random fast seeded: 4 Random fast seeded: 3 Random fast seeded: 2 </code></pre> <h1>uniformly distributed random numbers</h1> <p>If you are interested in uniformly distributed random numbers, you should see <strong>user3003631</strong>'s answer below. If you are in fact using C++, that's how I would recommend doing random numbers. <a href="http://www.cplusplus.com/reference/random/uniform_int_distribution/" rel="noreferrer">More information here too on this.</a></p>
 

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