随机生成数字放入数组(难度系数:1颗星)

来源:互联网 发布:js对象转化为字符串 编辑:程序博客网 时间:2024/06/07 14:56

随机生成1-6的数字放入到大小为56的数组中,保证数组最终每个数字出现的次数均为偶数。

参考代码1:

#include <stdio.h>#include <time.h>#define TOTALNUM 56int arr[TOTALNUM];int main(){    int i;    srand((unsigned int)time(NULL));    for (i = 0; i < TOTALNUM / 2; i++)        arr[i] = arr[i + TOTALNUM / 2] = rand() % 6 + 1;    for (i = 0; i < TOTALNUM; i++)    {        printf("%d ", arr[i]);        if ((i + 1) % (TOTALNUM / 4) == 0)            printf("\n");    }    return 0;}

运行结果:
这里写图片描述

参考代码2:

#include <stdio.h>#include <stdlib.h>#include <time.h>#define TOTALNUM 56int arr[TOTALNUM];void SwapArray(){    int i, nIndex1, nIndex2, nTemp;    for (i = 0; i < 100; i++)     {        nIndex1 = rand() % TOTALNUM;        nIndex2 = rand() % TOTALNUM;        if (nIndex1 != nIndex2)        {            nTemp = arr[nIndex1];            arr[nIndex1] = arr[nIndex2];            arr[nIndex2] = nTemp;        }    }}int main(){    int i;    srand((unsigned int)time(NULL));    for (i = 0; i < TOTALNUM / 2; i++)        arr[i] = arr[i + TOTALNUM / 2] = rand() % 6 + 1;    SwapArray();//随机进行100次交换,但并不是必须的    for (i = 0; i < TOTALNUM; i++)    {        printf("%d ", arr[i]);        if ((i + 1) % (TOTALNUM / 4) == 0)            printf("\n");    }    return 0;}

输出结果:
这里写图片描述

PS: 虽然在产生完成之后可以再加入SwapArray()函数进行一次随机交换操作(这是参考代码2和参考代码1的区别),但我认为这个并不是必须的,因为即使不进行这个操作,虽然数组的第1个数和第29个数会相同,但是我们并不能确定它是什么数字,依然满足随机性的定义。

3 0
原创粉丝点击