【发布时间】:2014-07-24 12:02:07
【问题描述】:
我正在尝试弄清楚如何对字符串中的字符进行随机排序,例如“this”、“htis”、“tish”或“hsit”。我相信我的问题在于 rand() 可能在循环中两次选择相同的随机数。比如第二个字符在循环中应用了两次。我也很确定,在循环的最后一次迭代期间,这个循环在某些时候也没有任何可供选择的东西。
我的代码如下:
int main(void){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
char word[size];
int i;
printf("Please enter a word: ");
scanf(" %s",&word);
printf("Scanning the size of the word...");
size = strlen(word);
for(i=0;i<size;i++){
srand(time(0));
int j = i + rand() / (RAND_MAX / (size - i) + 1);
char t = word[j];
word[j] = word[i];
word[i] = t;
}
printf("%i",size);
for(i=1;i<size+1;i++){
printf(" %c",word[i]);
}
return 0;
}
有什么想法吗?
【问题讨论】: