Returns a pseudo-random integral number in the range between 0 and RAND_MAX . This number is generated by an algorithm that returns a sequence of apparently ...
Search:
Reference
rand
function
rand
intrand(void);Generaterandomnumber
Returnsapseudo-randomintegralnumberintherangebetween0andRAND_MAX.
Thisnumberisgeneratedbyanalgorithmthatreturnsasequenceofapparentlynon-relatednumberseachtimeitiscalled.Thisalgorithmusesaseedtogeneratetheseries,whichshouldbeinitializedtosomedistinctivevalueusingfunctionsrand.
RAND_MAXisaconstantdefinedin.
Atypicalwaytogeneratetrivialpseudo-randomnumbersinadeterminedrangeusingrandistousethemoduloofthereturnedvaluebytherangespanandaddtheinitialvalueoftherange:
123
v1=rand()%100;//v1intherange0to99
v2=rand()%100+1;//v2intherange1to100
v3=rand()%30+1985;//v3intherange1985-2014
Noticethoughthatthismodulooperationdoesnotgenerateuniformlydistributedrandomnumbersinthespan(sinceinmostcasesthisoperationmakeslowernumbersslightlymorelikely).
C++supportsawiderangeofpowerfultoolstogeneraterandomandpseudo-randomnumbers(seeformoreinfo).
Parameters
(none)
ReturnValue
Anintegervaluebetween0andRAND_MAX.
Example
12345678910111213141516171819202122232425
/*randexample:guessthenumber*/
#include/*printf,scanf,puts,NULL*/
#include/*srand,rand*/
#include/*time*/
intmain()
{
intiSecret,iGuess;
/*initializerandomseed:*/
srand(time(NULL));
/*generatesecretnumberbetween1and10:*/
iSecret=rand()%10+1;
do{
printf("Guessthenumber(1to10):");
scanf("%d",&iGuess);
if(iSecretiGuess)puts("Thesecretnumberishigher");
}while(iSecret!=iGuess);
puts("Congratulations!");
return0;
}
Inthisexample,therandomseedisinitializedtoavaluerepresentingthecurrenttime(callingtime)togenerateadifferentvalueeverytimetheprogramisrun.
Possibleoutput:
Guessthenumber(1to10):5
Thesecretnumberishigher
Guessthenumber(1to10):8
Thesecretnumberislower
Guessthenumber(1to10):7
Congratulations!
Compatibility
InC,thegenerationalgorithmusedbyrandisguaranteedtoonlybeadvancedbycallstothisfunction.InC++,thisconstraintisrelaxed,andalibraryimplementationisallowedtoadvancethegeneratoronothercircumstances(suchascallstoelementsof).
Dataraces
Thefunctionaccessesandmodifiesinternalstateobjects,whichmaycausedataraceswithconcurrentcallstorandorsrand.
Somelibrariesprovideanalternativefunctionthatexplicitlyavoidsthiskindofdatarace:rand_r(non-portable).
C++libraryimplementationsareallowedtoguaranteenodataracesforcallingthisfunction.
Exceptions(C++)
No-throwguarantee:thisfunctionneverthrowsexceptions.
Seealso
srandInitializerandomnumbergenerator(function
)
C++
Information
Tutorials
Reference
Articles
Forum
Reference
Clibrary:
(assert.h)
(ctype.h)
(errno.h)
(fenv.h)
(float.h)
(inttypes.h)
(iso646.h)
(limits.h)
(locale.h)
(math.h)
(setjmp.h)
(signal.h)
(stdarg.h)
(stdbool.h)
(stddef.h)
(stdint.h)
(stdio.h)
(stdlib.h)
(string.h)
(tgmath.h)
(time.h)
(uchar.h)
(wchar.h)
(wctype.h)
Containers: