You can generate a unique range of random numbers like this. It works by creating a pool of all the available numbers, selects one at random, and then removes that number from the pool. The same method could be used for dealing a deck of cards, without the need to explicitly shuffle.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RANGE 9 // range of numbers
int main() {
int pool[RANGE];
int size, n;
for (size=0; size<RANGE; size++) {
pool[size] = size+1; // create number pool 1...
}
srand((unsigned)time(NULL));
while (size) { // generate random sequence
n = rand() % size; // random array index
printf("%d ", pool[n]); // select number from pool
pool[n] = pool[--size]; // remove from pool
}
printf("
");
return 0;
}
Here too is a debugged version of your program. Apart from bad array indexing, your mistake was to print from the array before the randomizing was finished.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i = 1, num[9] = {1,2,3,4,5,6,7,8,9};
srand((unsigned)time(NULL));
for (i=0; i<9; i++) {
int j = rand() % 9;
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
for (i=0; i<9; i++) {
if (i % 3 == 0)
printf("
%d: ", 1+i/3);
printf(" %i", num[i]);
}
printf("
");
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…