Random value in C ++

3

I was practicing a bit of C ++, I created that simple data-set exercise, so I came across a problem, how can I generate random values in C and C ++?

Taking a look at the site ( c plus plus ) found an example using time as seed (seed), the problem is after that, I created a code as an example, in it I'm creating a "Given" class and creating two methods, Seed and "Roll", one will create the seed and generate a value and the other will pass the fixed values and call Seed , inside main I instantiated 3 objects of type Dado and did the "scrolling", always drop the same values for the 3 objects, they are different instances , as in other languages, should not generate different values? This is the goal, create different values for each created data, follow the codes:

given.h

#ifndef DADO_H
#define DADO_H

#include <cstdlib>
#include <ctime>

class Dado
{
public:
    int Seed(int max, int min);
    int Rolar();
};

#endif

dado.cpp

#include "dado.h"

int Dado::Seed(int max, int min){
   srand(time(NULL));
    return rand() % max + min;
}

int Dado::Rolar(){
    int val_max = 6;
    int val_min = 1;
    return Seed(val_max, val_min);
}

main.cpp

#include <iostream>
#include "dado.h"

using namespace std;

int main()
{
    Dado seed;
    Dado dado_1;
    Dado dado_2;

    cout << "Seed:   " << seed.Seed(6,1) << "\n";
    cout << "Dado_1: " << dado_1.Rolar() << "\n";
    cout << "Dado_2: " << dado_2.Rolar() << "\n";

    return 0;
}

makefile to help anyone who wants to test

all: main
    rm *.o && ./teste

main: main.o dado.o
    g++ -g -o teste main.o dado.o -Wall

main.o: main.cpp dado.h
    g++ -c -g main.cpp -Wall

dado.o: dado.cpp dado.h
    g++ -c -g dado.cpp -Wall

I also created a demonstration in the ideone with a few changes, nothing that changes the result, just to organize the view (I do not use this tool very much , so I do not know if it works with more than one file to do cpp and header ).

    
asked by anonymous 12.03.2017 / 07:15

1 answer

4

The problem is that you are thinking that you should create a new seed every time you actually create the seed just once.

There are still two things that this code is not ideal. The random C generation that was used is not very suitable, it is best to use C ++ .

  • And this class is useless, the most you could do would be to encapsulate generation into a simple function. Creating a class for this is killing a bird with a cannon. So I made it as simple as possible. But remember the seed can only be generated once.

    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    using namespace std;
    
    int main() {
        srand(time(NULL));
        cout << "Dado_1: " << rand() % 6 + 1 << "\n";
        cout << "Dado_2: " << rand() % 6 + 1 << "\n";
    }
    

    See running on ideone . And at Coding Ground . Also I put it in GitHub for future reference .

        
  • 12.03.2017 / 08:04