随机数生成

遇到了这么个题

1949, 2012, 1946, 1874, 2046, 1994, 1839, 1824, 1999, 1024 
Choose one number from the ten numbers mentioned above. Only one is correct.

正好复习一下生成(伪)随机数的rand和srand...

time(0)获得从某个值得纪念的时刻(1970年1月1日0时)到调用time函数时经过的秒数

srand设置随机数种子,就是说种子相同时产生的“随机”序列也相同,不过每次使用不同的种子(使用time(0)),假装成是真随机就能凑合用了

rand(),得到0-RAND_MAX(在我的系统上是32767)之间的随机数,再取膜你想要的范围就行了

time()需要ctime头文件

srand,rand需要cstdlib

#include<cstdio>
#include<cstdlib>
#include<ctime>
int arr[10] = {1949, 2012, 1946, 1874, 2046, 1994, 1839, 1824, 1999, 1024};
int main()
{
    srand(time(0));
    int num = rand()%10;
    printf("%d", arr[num]);
    return 0;
}

交了四次成功AC,处于(勉强的)欧洲人水平

所以说到最后我也不知道答案是哪个数,interesting

posted @ 2017-07-17 22:00  DearDongchen  阅读(230)  评论(0编辑  收藏  举报