欢迎来到天天文库
浏览记录
ID:47544827
大小:28.00 KB
页数:3页
时间:2019-09-18
《function_rand》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、functionrandintrand(void);GeneraterandomnumberReturnsapseudo-randomintegralnumberintherange0toRAND_MAX.Thisnumberisgeneratedbyanalgorithmthatreturnsasequenceofapparentlynon-relatednumberseachtimeitiscalled.Thisalgorithmusesaseedtogeneratetheseries,whichshouldbeinitializedtosom
2、edistinctivevalueusingsrand.RAND_MAXisaconstantdefinedin.Itsdefaultvaluemayvarybetweenimplementationsbutitisgrantedtobeatleast32767.Atypicalwaytogeneratepseudo-randomnumbersinadeterminedrangeusingrandistousethemoduloofthereturnedvaluebytherangespanandaddtheinitialvalueoftheran
3、ge:(value%100)isintherange0to99(value%100+1)isintherange1to100(value%30+1985)isintherange1985to2014Noticethoughthatthismodulooperationdoesnotgenerateatrulyuniformlydistributedrandomnumberinthespan(sinceinmostcaseslowernumbersareslightlymorelikely),butitisgenerallyagoodapproximationfors
4、hortspans.Parameters(none)ReturnValueAnintegervaluebetween0andRAND_MAX.Example1234/*randexample:guessthenumber*/#include#include#includeintmain(){56789101112131415161718intiSecret,iGuess;/*initializerandomseed:*/srand(time(NULL));/*generatesecretnumber:*/iSec
5、ret=rand()%10+1;do{printf("Guessthenumber(1to10):");scanf("%d",&iGuess);if(iSecretiGuess)puts("Thesecretnumberishigher");}while(iSecret!=iGuess);puts("Congratulations!");return0;}Output:Guessthenumber(1to10):5Thesecretnumberishigher
6、Guessthenumber(1to10):8ThesecretnumberislowerGuessthenumber(1to10):7Congratulations!Inthisexample,therandomseedisinitializedtoavaluerepresentingthesecondinwhichtheprogramisexecuted(timeisdefinedintheheader).Thiswaytoinitializetheseedisgenerallyagoodenoughoptionformostrandomingne
7、eds.
此文档下载收益归作者所有
点击更多查看相关文章~~