A
A
Alexander Vasilenko2016-04-03 10:17:33
C++ / C#
Alexander Vasilenko, 2016-04-03 10:17:33

rand() works strangely. What is the problem?

Hey! I have a function:

char generate_asterisk_or_space() {
  srand(static_cast<int>(time(0)));
  int num = rand() % 2;
  switch (num) {
  case 0:
    return '_';
  case 1:
    return '*';
  default:
    return '_';
  }
}

Its essence is to simply return * or _. With it, I form an array, but! It produces exactly the same characters during a normal launch ... Oops!
Another but, is that if I debug the code step by step, everything works as expected - a random set of characters is formed. Tried some tricks with time delay and passing different parameters to srand() - didn't help.
What is the reason for such strange behavior?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2016-04-03
@SanchelliosProg

Set the seed once - before forming the array. With a release build, the value returned by time is most likely the same. Example:

srand(static_cast<int>(time(0)));
for( int i =0; i<array_length; i++){
     rand_array[i] = generate_asterisk_or_space();
}

J
jcmvbkbc, 2016-04-03
@jcmvbkbc

With it, I form an array,

Those. you call it in a loop, i.e. call srand(static_cast(time(0))); many times in a short time. Continue?
Question: why are you doing this inside this function?

A
AxisPod, 2016-04-06
@AxisPod

And how else to work if the same starting value is always set?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question