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 ).