我一直在弄清楚如何在用户使用 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;
最佳答案
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]);
}
关于c - 用数字从数组中打乱数字 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25540451/