博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
srand和rand的用法
阅读量:4286 次
发布时间:2019-05-27

本文共 1424 字,大约阅读时间需要 4 分钟。

srand((unsigned)time(NULL))是初始化随机函数种子:
1、是拿当前系统时间作为种子,由于时间是变化的,种子变化,可以产生不相同的随机数。
计算机中的随机数实际上都不是真正的随机数,如果两次给的种子一样,是会生成同样的随机序列的。 所以,一般都会以当前的时间作为种子来生成随机数,这样更加的随机。 
2、使用时,参数可以是unsigned型的任意数据,比如srand(10); 3、如果不使用srand,用rand()产生的随机数,在多次运行,结果是一样的。
void test_rand(void)
{           unsigned long n;          srand((unsigned)time(NULL));          for(int i = 0; i < 100; i++)          {                n = rand();                printf("d\n", n);           }}
int rand (void);  
Generate random number
Returns a pseudo-random integral number in the range between 0 and .This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function .  is a constant defined in . A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:
123
v1 = rand() % 100; // v1 in the range 0 to 99v2 = rand() % 100 + 1; // v2 in the range 1 to 100v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
 
Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely)

转载地址:http://evxgi.baihongyu.com/

你可能感兴趣的文章
swift之字符串名转类名NSClassFromString
查看>>
swift之按钮的使用
查看>>
swif之Tableview的使用、cell动态高度、侧滑删除、设置中心、个人中心、cell多选、cell单选
查看>>
swift之自动布局,系统自带的布局、SnapKit布局
查看>>
swift之自动计算字符串文本大小
查看>>
swift之View向上偏移的解决
查看>>
swift之颜色、16进制颜色转换成RGB颜色
查看>>
swift之UICollectionView的使用、cell多选
查看>>
swift之代理的使用
查看>>
swift之通知的使用
查看>>
swift之UIWebview的使用
查看>>
iOS之JavaScript与OC的相互调用:WKwebview 的使用
查看>>
swift之wkwebview的使用
查看>>
swift之URLSession的使用
查看>>
swift中KVO的使用和注意事项、属性观察器
查看>>
swift之GCD的使用
查看>>
swift之UIAlertController
查看>>
swift之视频播放AVKIT、AVPlayerViewController、音频录制和播放
查看>>
android之res/menu
查看>>
android之通知Notification
查看>>