简单C随机抽奖号码

Simple C random lottery number

我想用最简单的方法生成5个不同的数字,然后把它们放到一个数组中。我的思路有问题,请指正我的代码好吗?

void lottery(int *array){
    int i = 0;
    while(i != 5){
        bool good = true;
        int number = rand()%90+1;
        for(int j=0; j<5; j++){
            if(array[j] == number)
                good = false;
                break;

        }
        if(good){
            array[i] == number;
            i = i+1;
        }
    }
}

int main(){
    srand(time(0));
    int numbers[5];
    lottery(numbers);

    for(int i =0; i<5; i++){
        printf("%d, ",numbers[i]);
    }
    return 0;
}

包括 kingW3rici 的发现并稍微清理一下:

// compiles without errors with:
// clang -O3 -g3 -Weverything -W -Wall -Wextra -Wpedantic -fsanitize=bounds  -std=c11  -o stacktest stacktest.c 
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

void lottery(int *array);
void lottery(int *array){
    int i = 0;
    while(i != 5){
        bool good = true;
        int number = rand()%90+1;
        // limit is 'i' because you fill the array in order
        for(int j=0; j<i; j++){
            // Would always `break` without the curly brackets
            if(array[j] == number){
                good = false;
                break;
            }
        }
        if(good){
            // Use '=' instead of '=='
            array[i] = number;
            i = i+1;
        }
    }
}

int main(void){
    // time returns type 'type_t', needs casting to get rid of
    // warning
    srand( (unsigned int) time(0));
    // return of rand() is always >= 0, so 
    // initialize with a negative number
    int numbers[5] = {-1};
    int i;
    lottery(numbers);
    for(i =0; i<4; i++){
        printf("%d, ",numbers[i]);
    }
    printf("%d\n",numbers[i]);
    return 0;
}

缺少括号是另一个错误。

注意:time() 的分辨率很可能是一秒,所以不要 运行 顺序太快,否则你会得到相同的数字。