0

我想以最简单的方式生成 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;
}
4

1 回答 1

2

包括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()很可能有一秒的分辨率,所以不要按顺序运行太快,否则你会得到相同的数字。

于 2018-10-22T22:54:19.210 回答