Jump to content
Forum Roportal
The Builder

Random number

Rate this topic

Recommended Posts

Worca27 sunt si eu curios ca tot omul cum genereaza prcesorul un numar random:cu multe operatii matematice sau se extrage cu ajutorul unui algoritm un numar din ceasul sistemului??

Share this post


Link to post
Share on other sites

generarea aleatoare a unui singur numar:

 

#include <cstdlib>

#include <iostream>

 

using namespace std;

 

int main()

{

int random_integer = rand();

cout << random_integer << endl;

}

Share this post


Link to post
Share on other sites

#include <cstdlib>

#include <ctime>

#include <iostream>

 

using namespace std;

 

int main()

{

srand((unsigned)time(0));

int random_integer = rand();

cout << random_integer << endl;

}

Share this post


Link to post
Share on other sites

... sau generarea unui numar intre anumite valori

 

#include <cstdlib>

#include <ctime>

#include <iostream>

 

using namespace std;

 

int main()

{

srand((unsigned)time(0));

int random_integer;

for(int index=0; index<20; index++){

random_integer = (rand()%10)+1;

cout << random_integer << endl;

}

}

Share this post


Link to post
Share on other sites

... sau ceva mai complicat, generarea aleatoare a 20 numere intre 1 so 10

 

 

#include <iostream>

#include <ctime>

#include <cstdlib>

 

using namespace std;

 

int main()

{

srand((unsigned)time(0));

int random_integer;

int lowest=1, highest=10;

int range=(highest-lowest)+1;

for(int index=0; index<20; index++){

random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));

cout << random_integer << endl;

}

}

Share this post


Link to post
Share on other sites

Numarul nu e aleator, ci pseudo-aleator. Adica se genereaza o secventa de numere folosind un algoritm matematic, numere ce par aleatoare. Valoarea de la care se porneste se numeste seed, si poate fi de exemplu timpul curent (in milisecunde).

Un algoritm simplu ar fi (seed*49 mod 50) care returneaza numere intre 0 si 49. Bineinteles ca e doar ceva cu rol de exemplu, in realitate trebuie asigurata o distributie propice si un mod de a evita intrarea intr-o bucla.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×