【0003】与随机数有关的一些问题
时间种子的随机数的生成,需要#include <time.h>。
#include <time.h> time_t ts; unsigned int num = time(&ts); srand(num); // 或者 srand((unsigned int)(time(NULL)));
001、洗牌
#include <stdio.h> #include <stdlib.h> #include <time.h> void main() { int a[54]; for (int i = 0; i < 54; i++) printf("%d ", a[i] = i); srand((unsigned int)time(NULL)); // 随机数种子 for (int i = 0; i < 53; i++) { int num = i + rand() % (53 - i); // 洗牌核心 int temp = a[i]; a[i] = a[num]; a[num] = temp; } puts(" "); for (int i = 0; i < 54; i++) printf("%d ", a[i]); getchar(); }