3
I was practicing a little C++, I created that simple data game 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) I found an example using time as Seed (seed), the problem is after that, I created a code as an example, in it I am creating a class "Data" and creating two methods, the Seed
and the "Roll", one will create the seed and generate a value and the other will pass the fixed values and call the Seed
, within the main
I installed 3 objects of the type Dado
and I did the "scrolling", always fall the same values for the 3 objects, 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:
data. h
#ifndef DADO_H
#define DADO_H
#include <cstdlib>
#include <ctime>
class Dado
{
public:
int Seed(int max, int min);
int Rolar();
};
#endif
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 demo on ideone with some changes, nothing that changes the result, just to organize the visualization (I don’t use this tool much, so I don’t know if it works with more than one file to do the cpp
and header).
the website "c plus plus" nay is official documentation...the official documentation is provided by ISO through member countries (for example here)...Normally the "Working Drafts" of the C++ standardization committee are sufficient as documentation, and are easily accessible (here )... moreover the site cpp Reference is generally considered better than "c plus plus plus"
– zentrunix
Okay, sorry, I thought it was the official website, even by his organization, I’ll check it out better on that cpp.
– bruno101
The so-called and official documentation is nothing official, it is one of the principles, the best is http://en.cppreference.com/w/
– Maniero