我有点难把我的话按随机顺序打印出来。我插入的8个单词需要按随机顺序打印出来。现在我只能以随机顺序生成其中的一些,因为如果同一个数字生成两次,它会覆盖前面的空格。如何消除此问题?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#define MAX 50
int readLine(char string[]);
int main(void)
{
int i;
char str[8][MAX], temp[8][MAX];
srand((unsigned)time(NULL));
int r_num;
printf("Enter 8 words:\n");
for(i=0; i<8; ++i)
{
readLine(str[i]);
}
for (int i = 0; i < 8; i++)
{
r_num = rand()%8+1;
strcpy(temp[r_num], str[i]);
}
printf("\nRandom order of words: \n");
for(i=0; i<8; ++i)
{
printf("%s\n", temp[i]);
}
printf("\n");
return 0;
}
int readLine(char string[])
{
int ch;
int i=0;
while (isspace(ch = getchar()))
;
while (ch != '\n' && ch != EOF)
{
if (i < MAX)
{
string[i++] = ch;
ch = getchar();
}
}
string[i] = '\0';
return i;
}
最佳答案
洗牌数据的方法之一是从尚未选择的内容中进行挑选。
int main(void)
{
int i;
char str[8][MAX];
int order[8]; /* order list */
srand((unsigned)time(NULL));
int r_num;
printf("Enter 8 words:\n");
for(i=0; i<8; ++i)
{
readLine(str[i]);
}
/* initialize order list */
for (i = 0; i < 8; i++)
{
order[i] = i;
}
for (i = 7; i > 0; i--) /* select from back to front */
{
int pos = rand() % (i + 1); /* pick one position randomly */
/* pick selected element by swapping */
int temp = order[pos];
order[pos] = order[i];
order[i] = temp;
}
printf("\nRandom order of words: \n");
for(i=0; i<8; ++i)
{
printf("%s\n", str[order[i]]); /* print strings in the shuffled order */
}
printf("\n");
return 0;
}
关于c - 输入字符串并以随机顺序打印,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40681567/