日常踩坑——rand()总是出现重复数据

写了一个生成随机数组的函数,然后跑出来,结果总是……

然后,很奇怪的是一步一步调试,它就没问题了,WTF???

问题出在:重复写了srand(time(NULL)),只保留一个就好了。

int* getRandomArray(int size, int value) {
    //srand((unsigned)time(NULL));
    int *a = new int[size];
    for (int i = 0; i < size; i++) {
        a[i] = (rand() % value) - (rand() % value);
    }
    return a;
}

int main() {
    srand((unsigned)time(NULL));
    for (int i = 0; i < 15; i++) {
        int *a = getRandomArray(15, 100);
        for (int i = 0; i < 15; i++)cout << a[i] << " ";
        cout << endl;
        delete[]a;
        a = NULL;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/czc1999/p/10277181.html