How to generate a random number in C++?

2020-01-22 12:44发布

I'm trying to make a game with dice, and I need to have random numbers in it (to simulate the sides of the die. I know how to make it between 1 and 6). Using

#include <cstdlib> 
#include <ctime> 
#include <iostream>

using namespace std;

int main() 
{ 
    srand((unsigned)time(0)); 
    int i;
    i = (rand()%6)+1; 
    cout << i << "\n"; 
}

doesn't work very well, because when I run the program a few times, here's the output I get:

6
1
1
1
1
1
2
2
2
2
5
2

So I want a command that will generate a different random number each time, not the same one 5 times in a row. Is there a command that will do this?

标签: c++ random
10条回答
太酷不给撩
2楼-- · 2020-01-22 13:06

Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it's perfectly possible to get repeating numbers in a random sequence.

Try some C++11 features for better distribution:

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

See this question/answer for more info on C++11 random numbers. The above isn't the only way to do this, but is one way.

查看更多
一纸荒年 Trace。
3楼-- · 2020-01-22 13:07

Can get full Randomer class code for generating random numbers from here!

If you need random numbers in different parts of the project you can create a separate class Randomer to incapsulate all the random stuff inside it.

Something like that:

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /*  ... some convenient ctors ... */ 

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

Such a class would be handy later on:

int main() {
    Randomer randomer{0, 10};
    std::cout << randomer() << "\n";
}

You can check this link as an example how i use such Randomer class to generate random strings. You can also use Randomer if you wish.

查看更多
Root(大扎)
4楼-- · 2020-01-22 13:08

Here is a solution. Create a function that returns the random number and place it outside the main function to make it global. Hope this helps

#include <iostream>
#include <cstdlib>
#include <ctime>
int rollDie();
using std::cout;
int main (){
    srand((unsigned)time(0));
    int die1;
    int die2;
    for (int n=10; n>0; n--){
    die1 = rollDie();
    die2 = rollDie();
    cout << die1 << " + " << die2 << " = " << die1 + die2 << "\n";
}
system("pause");
return 0;
}
int rollDie(){
    return (rand()%6)+1;
}
查看更多
霸刀☆藐视天下
5楼-- · 2020-01-22 13:15

Here is a simple random generator with approx. equal probability of generating positive and negative values around 0:

  int getNextRandom(const size_t lim) 
  {
        int nextRand = rand() % lim;
        int nextSign = rand() % lim;
        if (nextSign < lim / 2)
            return -nextRand;
        return nextRand;
  }


   int main()
   {
        srand(time(NULL));
        int r = getNextRandom(100);
        cout << r << endl;
        return 0;
   }
查看更多
Animai°情兽
6楼-- · 2020-01-22 13:20

The most fundamental problem of your test application is that you call srand once and then call rand one time and exit.

The whole point of srand function is to initialize the sequence of pseudo-random numbers with a random seed. It means that if you pass the same value to srand in two different applications (with the same srand/rand implementation) you will get exactly the same sequence of rand() values read after that. But your pseudo-random sequence consists of one element only - your output consists of the first elements of different pseudo-random sequences seeded with time of 1 second precision. So what do you expect to see? When you happen to run application on the same second your result is the same of course (as Martin York already mentioned in a comment to the answer).

Actually you should call srand(seed) one time and then call rand() many times and analyze that sequence - it should look random.

查看更多
爷、活的狠高调
7楼-- · 2020-01-22 13:23

for random every RUN file

size_t randomGenerator(size_t min, size_t max) {
    std::mt19937 rng;
    rng.seed(std::random_device()());
    //rng.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);

    return dist(rng);
}
查看更多
登录 后发表回答