随机数彼此不匹配

我想用C生成不同的数字。 我们可以使用stdlib库和srand函数生成一个随机数。

例如; 我想生成0到5之间的随机数。

 #include  #include  #include  int main(void) { int i; int n = 4; int array[3]; srand(time(NULL)); for(i = 0; i < n; i++) { array[i] = rand() % 5; printf("%d\n", array[i]); } return 0; 

但是相同的数字可能在这里重合。就像这样:

 2 4 4 1 

我怎么能阻止这个?

也许你可以使用这样的东西:

 #include  #include  #include  int main(void) { int i; int n = 4; int array[4]; // Fill an array with possible values int values[5] = {0, 1, 2, 3, 4}; srand(time(NULL)); for(i = 0; i < n; i++) { int t1 = rand() % (5-i); // Generate next index while making the // possible value one lesser for each // loop array[i] = values[t1]; // Assign value printf("%d\n", array[i]); values[t1] = values[4-i]; // Get rid of the used value by // replacing it with an unused value } return 0; } 

您可以从前一个数字生成随机非零移位,而不是随机数:

 #include  #include  int myrand() { static int prev = -1; if (prev < 0) prev = rand() % 5; prev = (prev + 1 + rand() % 4) % 5; return prev; } int main(void) { int i; for (i = 0; i < 20; i++) printf("%d\n", myrand()); }