带数字的数组中的扰码 - C

时间:2014-08-28 03:54:40

标签: c arrays random

在用户使用rand()输入10个不同的数字后,我一直在想弄清楚如何从数组中加扰数字。当它到达adjust()函数时会崩溃,所以请随意指出我的愚蠢错误。干杯。顶部是功能,底部是main()。

void adjust(int z[], int size)
{
    int i, n, t;

    for(i = 0; i < size; i++)
    {
        size = rand();
        t = z[size];
        z[size] = z[i];
        z[i] = t;
    }

    printf("\nYour numbers have been scrambled and here they are: \n", t);
}

.....................

int z[10];
int i;
int num = 0;

printf("Please enter 10 different numbers: \n");

for(i = 0; i < 10; i++)
{
    z[i] = num;
    scanf("%d", &num);
}

printf("\nThe numbers you entered were: ");

for (i = num; i <= 10; i++)
{
    printf("%d ", z[i]);
}
printf("\n");

addNum(z, 10);

adjust(z, 10);

return 0;

1 个答案:

答案 0 :(得分:3)

rand()函数返回0到RAND_MAX之间的数字。 因此,数组索引可以远远超出其范围。

要获得0到N -1范围内的随机索引,请使用rand()%N。

另一个问题是,在你的for循环中,在adjust函数中,你正在破坏'size'的原始值。它包含数组的长度,用于检查for循环的终止条件。因此,请勿修改“大小”。使用另一个变量来存储随机索引。

for(i = 0; i < size; i++)
{
    n = rand() % size;   // n is between 0 and size-1
    t = z[n];
    z[n] = z[i];
    z[i] = t;
}

// For a better design move the following lines to a separate function
// that way adjust function just does the scrambling while another
// printing function prints out the array. Each function does only one thing.
printf("\nYour numbers have been scrambled and here they are: \n");
for( i = 0; i < size; i++)
{
   printf("%d ", z[i]);
}