简体   繁体   中英

C++ random function not random

In my c++ code I have a problem. My random drawBlock function which should return xRandom and yRandom is not so random.

void Game::drawBlock() 
{
    int xRandom, yRandom;
    std::cout<<time(NULL) << std::endl;
    xRandom =  (rand () % 620) + 1;
    yRandom =  (rand () % 440) + 1;
    std::cout << "x: " << xRandom << std::endl;
    std::cout << "y: " << yRandom;
    mBlock.setSize(sf::Vector2f(20,20));
    mBlock.setPosition(xRandom,yRandom);
    mBlock.setFillColor(sf::Color::Red);
}

so what basically happens is that the first random number, in this case xRandom isn't really random. When I run the program everything seems fine xRandom gets a random number and yRandom gets a random number. But when I restart the program my xRandom number is almost the same. while my yRandom number changes completely. so for example when I start my code: xRandom = 33 yRandom = 381 when I than re-run my code xRandom = 41 and after re-running it for 10 times is looks something like this: 55,66,84,101,125,140,180,201,234,251 Something strange is that the new xRandom is always more than the last one.

Here is the code were I call srand:

#include <SFML/Graphics.hpp>
#include "Game.h"

int main()
{
    srand(time(0));
    Game game;
    game.run();
    return 0;
}

You're usage of rand() seems to be relatively standard. rand() is infamous as a poor source of random data and perhaps the implementation you're using is simply worse than usual in this particular way. You might find a solution that allows you to use that particular implementation, but I'd suggest moving to another source of random numbers.

C++11 introduced the <random> library which provides random facilities with guaranteed qualities, is more powerful and flexible, and is easier to use. It should be preferred whenever it is available.

To use the <random> library in C++11 you create and seed a source of randomness:

#include <random>

std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 engine(seed);

And then use 'distributions' to take random data from the engine and produce random numbers:

std::uniform_int_distribution<> dist(1, 6);
int die_roll = dist(engine);

For your usage you would probably have the engine be a member of Game :

class Game {
  std::mt19937 engine;
// ...

And then in drawBlock() :

xRandom = std::uniform_int_distribution<>(1, 620)(engine);
yRandom = std::uniform_int_distribution<>(1, 440)(engine);

Here is how I did it:

int a;
srand(time(NULL));
a=rand()%100+1

It worked for me, to generate a random number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM