c++randomsfmlreplitflappy-bird-clone

I am having an error with the random function in replit c++


I am working on a flappy bird clone to help me learn c++ and SFML. I am working on the pipes, and finally got a working version, but for some reason every time I run the code the rand() function gives me the same result every time.

class Pipes
{
    float x;
    int y;

public:
    Pipes();

        
    void draw(RenderWindow& i_window);
    void update();
};

Pipes::Pipes() :
    y(-(rand() % 175) - 450), // every time I run it, this is -458.
    x(200)
{
    std::cout << y;
}

I am trying to get a number between -450 and -625.

As requested, here is an MRE (i still haven't found the solution):

#include <iostream>
#include <cmath>

class Random
{
    int rndm;

public:
    Random();

};

Random::Random() :
    rndm((rand() % 175) - 450)
{
    std::cout << rndm;
}


int main() {
    Random random;
}

Solution

  • Try using <random> library

    #include <iostream>
    #include <random>
    int main()
    {    
        const int range_from  = 450;
        const int range_to    = 625;
        std::random_device                  rand_dev;
        std::mt19937                        generator(rand_dev());
        std::uniform_int_distribution<int>  distr(range_from, range_to);
    
        std::cout << -distr(generator) << '\n';
    }