Distribution addicted when using the Rand() function

Asked

Viewed 69 times

1

Hello, how do I use the function rand() with the range Y [11, height+9] and X [11, width-1].

srand (time(NULL));
y=rand() % ((altura+9)-11) + 11;
x=rand() % ((largura-1)-11) + 11;

gotoXY(x, y);
cout<<"o";

Is that how it is? It is happening that it is generating many repeated numbers, and the interval should be large

Fills only this space in a cycle for(;;) in half a minute, where width = 70 and height = 25:

posições geradas

One of the problems is to loop this code in case I take srand (time(NULL)); It can already generate numbers well, but if I close the program and open again will generate with the same pattern, what I did not want this

  • What is the maximum and minimum value of X and Y?

  • I want to generate 2 integers, a Y and a X. O Y I want the range to be [11 the height+9] O X I want it to be [ 11 the width-1] Width and height is incognita

  • If this is the case, the formulas appear to be correct.

  • That @Andersoncarloswoss, I couldn’t write that way

  • The problem is that it’s generating several equal numbers, it’s not taking the whole range

  • It would be something like, y: rand() % (altura + 9) + 11 and x: rand() % (largura-1) + 11? fished from doc. I don’t understand the -11 in your code

  • What is the value of altura and largura? I imagine they’re small, given the gotoXY.

  • How often do you run this? What kind of very repeated numbers are you having?

  • I already edited the post, with more information

  • 2

    I already know the answer: You are running the srand (time(NULL)); within the for (;;). This will make it regenerate the same values always until the clock changes. Move this statement to before the for.

  • Exactly @Victorstafusa, can you explain why this is happening? I would like to understand

  • 1

    The srand will use the parameter to generate a sequence of numbers. The first call following the rand() will get the first number of that sequence. The second subsequent call, the second number, etc. However, if you call the srand again, it will restart a new sequence. As the parameter you use in srand will be the same, time it changes slowly, it will always restart in the same sequence and with that keep generating repeated X and Y values until the clock changes.

  • @Thank you so much for your help. Thank you to everyone who helped!

Show 8 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.