0

I'm writing a code that will return a random number between 5 and 20, and i'm running into a problem where it will always produce the same number over again and i can't seem to solve it.

#include <stdlib.h>
#include <stdio.h>

int random = 0;

int randomnumbergen() {
srand(12345);
random = rand() % (20 - 15) + 15;
return random;
}
  • Not really a miracle - you seed the random number generator with the same value all them time! – Eugen Rieck Feb 19 '15 at 00:10
  • Once you get `srand()` fixed, I think you'll still have problems with `random = rand() % (20 - 15) + 15;`. – FoggyDay Feb 19 '15 at 00:14
  • @FoggyDay: it depends on whether the typo is in the code or the statement of the range. IIRC, you need a `+1` in the modulo range to get the 6 numbers 15..20 (or 16 numbers from 5..20). – Jonathan Leffler Feb 19 '15 at 00:15
  • See also: [Recommended way to initialize `srand()`](http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand) – Jonathan Leffler Feb 19 '15 at 00:27

2 Answers2

2

First, you'll want to call srand() at the beginning of your program one time.

Next, you'll want to replace

srand(12345);

with

srand (time(NULL));
vdelricco
  • 749
  • 4
  • 15
  • This will still cause the same number to be returned *if randomnumbergen() is called repeatedly in a tight loop*. – Eric J. Feb 19 '15 at 00:13
  • @EricJ. true, but at least a step ahead of using the same number every time. – Jonathan Leffler Feb 19 '15 at 00:14
  • @JonathanLeffler: I would argue it is worse, because a unit test for the function that does not consider the temporal factor may well show it "working", while it fails when used in a loop. Effectively, the bug is better hidden. – Eric J. Feb 19 '15 at 00:15
0

You're using the same seed each time - producing identical results. You need to not hardcode it.

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
Maxwell S
  • 135
  • 9
  • 2
    But removing the call to `srand()` also leaves the results deterministic, albeit with a different sequence. You need to call `srand()` with a different number each time. Consider reading a random number from `/dev/urandom`. – Jonathan Leffler Feb 19 '15 at 00:12
  • 1
    The observation is correct, the proposed solution is system specific. – Eric J. Feb 19 '15 at 00:13
  • @EricJ. The suggested solution works on most modern variants of Unix (Mac OS X, Linux I've tested this year; I think it works on Solaris, but I've not used it for a couple of years now - I'm not sure about HP-UX and AIX). There isn't a more portable solution to getting a reasonably good random seed that I'm aware of. – Jonathan Leffler Feb 19 '15 at 00:17
  • @JonathanLeffler: C also works on Windows, DOS and embedded systems not based on Linux. The question is not tagged Linux. – Eric J. Feb 19 '15 at 00:19
  • Well, you have to remember that C can run on Windows, too... – Maxwell S Feb 19 '15 at 00:20