如何使用C从列表中选择一个随机数,仅一次

not*_*ihs 1 c arrays random srand

所以我有一个从0到27的整数数组.

for(i<0; i<28; i++)
{
    ListId[i] = i;
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是从该数组中选择一个数字并随机地在另一个数组中重新排序.

我试图通过一个标志,数字-1替换已经选择的数字:

for(i<0; i<28; i++)
{
    RandomId[i] = i;
    ListId[i] = i;
}

srand(time(NULL));

for(i=0; i<28; i++)
{
    res = rand() % 27;
    aux = ListId[res];

    if (ListId[res] != -1)
    {
        RandomId[i] = aux;
        ListId[res] = -1;
    }
    else
        i--;
}

printf("New list of integers: ");

for(i=0; i<28; i++)
{
    printf("%d | ", RandomId[i]);
}
Run Code Online (Sandbox Code Playgroud)

但最终变成了无限循环.

希望可以有人帮帮我.

先感谢您

Dro*_* K. 5

注意你的第一个for循环: for(i<0;i<28;i++)

注意你的:res = rand() % 27;......应该28.

范围% N是0到(N-1),因此你的27个结果的范围是0-26.