How to use random in C ++?

9

I would like an example of using the random in C ++ because I need to use it but I do not know how it works.

    
asked by anonymous 16.05.2015 / 17:16

2 answers

4

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 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 );
  }
}
    
16.05.2015 / 19:01
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

    
17.05.2015 / 04:35