How to use random in C++?

Asked

Viewed 325 times

8

I would like an example of the use of random in C++, because I need to use it but I don’t know how it works.

2 answers

7

#include <random>
#include <iostream>

int main() {
    using namespace std;

    random_device rng; // Gerador de números randômicos próprio para gerar seeds.
    mt19937 prng(rng()); // Gerador pseudo-randômico Mersenne Twister inicializado com uma seed.
    uniform_int_distribution<int> random(1, 10); // Distribuição uniforme para números de 1 à 10.
    cout << random(prng) << endl; // Gera um número de 1 à 10 uniformemente via Mersenne Twister.
    cout << random(prng) << endl; // Gera outro número de 1 à 10 uniformemente via Mersenne Twister.
}

online result

  • #include <random> does not work in the devC++

  • @Rodolfo the best you have to do is to stop using Devc++. This is a very outdated IDE and is not used by any desktop environment. Even so, since it uses gcc, make sure that the gcc version of it supports the -Std=c++11 flag, if so, it is just use it to work, otherwise stop using this environment and adopt another one. Have much better free and free alternatives.

  • beauty I’ll check

3


The code below generates 10 random numbers from 0 to 10; if you random numbers with a longer range, just change the line item = rand() % 100; (now it will generate 10 elements with the range from 0 to 100.

int main(int argc, char *argv[]){
  int i;
  int item;
  for ( i = 1; i <= 10; i++ ) { 
    item = rand() % 10;
    printf( "%3d ", item );
  }
}
  • was not to generate random numbers, all made out the same number.

  • Rodolfo, you must feed with a Seed value to generate the random numbers. Search on srand.

Browser other questions tagged

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