利用系统的随机函数生成唯一随机数

遍历生成的一组随机数,让各个数唯一

#include
#include
void randLotteryNumber(short *rightlotteryNO,int size)
{
    int i = 0,j = 0,flag;
    short randNum = 0;
    //第一步,设置随机种子    
    unsigned int timeSeed = time(NULL);
    srand(timeSeed);
    while(1)
    {
        //产生随机数
        flag = 0;
        randNum = (short)(1+rand()%31);
        printf("%d\n",randNum);
        for(i = 0;i < size;i++)
        {
            if(rightlotteryNO[i] == randNum)
            {
                flag = 1;
                break;          
            }                               
        }
        if(0 == flag)
        {
            rightlotteryNO[j] = randNum;

            printf("randNum = %d\n",randNum);
            printf("rightlotteryNO[%d] = %d\n",j,rightlotteryNO[j]);
            j++;
            if(j == 7) break;
        }
    }
    printf("\n-----------\n");
}

int main()
{
    short rightlotteryNO[7];
    int i = 0;
    randLotteryNumber(rightlotteryNO,7);
    for(i = 0;i < 7;i++)
    {
        printf("%hd\t",rightlotteryNO[i]);                          
    }
    printf("\n");
}

/*

int main()
{

    int i = 0;
    int a[5];
    for(i = 0;i < 5;i++)
    {
        a[i] = rand()%10;
        printf("%d\t",a[i]);
    }
    return 0;   
}*/

你可能感兴趣的:(C)