简体   繁体   English

简单的C随机彩票号码

[英]Simple C random lottery number

I would like to generate 5 different numbers in the simplest way and put them into an array. 我想以最简单的方式生成5个不同的数字,并将它们放入数组中。 Something is wrong with my way of thinking, could you please correct my code? 我的思维方式出了点问题,您能否更正我的代码?

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;
}

Including the findings of kingW3 and rici and cleaning it up a little: 包括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;
}

The missing brackets were another error. 缺少的括号是另一个错误。

Caveat: time() has most probably a resolution of one second, so don't run it too fast in sequence or you'll get the same numbers. 警告: time()的分辨率很可能是一秒,因此不要按顺序运行它太快,否则会得到相同的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM