Dec 16, 2011

Get random numbers in C + + (rand, srand)


It happens very often, when you've mastered all that to ask for and store data, now your teacher asks you to generate random numbers your software to automate the process of completing arrangements and all that.
So the first thing we have to do is include the library:
#include<stdlib.h>
Then initialize the random numbers including this:
srand(time(NULL));
* Update: why not throw some mistake with IDE's time function. Well just use the library time.h:
#include<time.h>
Then save the random number somewhere:
num=rand();
That's basically. To set the random number range can do several things.
Random number between 0 and 50:
num=rand()%51;
Random number between 1 and 100:
num=1+rand()%(101-1);
Random number between 250 and 420:
num=250+rand()%(421-250);
In general form is:
variable = limite_inferior + rand() % (limite_superior +1 - limite_inferior) ;
So a program that displays 10 random numbers between 1 and 10 would read:
 Stdlib.h
 # Include <iostream>
 using namespace std;

 int main ()
 {
     int num, c;
     srand (time (NULL));
     for (c = 1, c <= 10, c + +)
     {
         num = 1 + rand ()% (11 - 1);
         court <<num <<"";
     }
     cin. get ();
 } 

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes