Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

Random lottery number generator in C programming

I want to do generate 7 different number (0-9) - first digit should not be 0- and put them into an array. Every number should be unique. I know what I did wrong but I dont know what should I do.

int arr[7], j, i;
    srand(time(NULL));
    for (i = 0; i < 7; i++)
    {
        arr[i] = rand() % 10;
                if (arr[0] == 0) 
                arr[0] = rand() % 10;
}
    for (i = 0; i < 7; i++)
    {
        for (j = 0; j < 7; j++)
        {
            
            if (i == j) {
                j++;
            }
            if (arr[i] == arr[j])
                arr[j] = rand() % 10;
    
        
        }
    }
    printf("
");
    for(j=0;j<7;j++)
            printf("
%d ", arr[j]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • You can use rand() % 9 + 1 to produce random number between 1 and 9.
  • arr[j] may be out-of-range after j++;.

Try this:

int arr[7], j, i;
srand(time(NULL));
arr[0] = rand() % 9 + 1; /* decide first number with special formula */
for (i = 1; i < 7; i++) /* decide the rest numbers */
{
    int dupe = 0;
    arr[i] = rand() % 10;
    for (j = 0; j < i; j++) /* check against numbers that already decided */
    {
        if (arr[i] == arr[j])
            dupe = 1; /* ouch, this number is already used! */
    }
    if (dupe)
        i--; /* if the number is already used, try again */
}
printf("
");
for(j=0;j<7;j++)
    printf("
%d ", arr[j]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...