我必须解决以下问题:
以下不完整的代码说明了一个程序,该程序由包含16个已排序名称的数组组成。程序的最后部分在屏幕上显示这些名称。您需要在标有空矩形的部分中编写代码,以便对名称进行重新排序。输出名称时,不应以升序输出,而是以随机顺序输出。您只需要在检查脚本中编写缺少的代码,而不是整个程序。
如何以最简单/直观的方式编写此代码?
#include <stdio.h>
#include <time.h>
int main(void)
{
int i, j, k;
char temp[20];
char names[16][20] = { "Anne" , "Carmen" , "David" , "Jesmond" ,
"John" , "Joseph" , "Karen" , "Kevin" ,
"Manuel" , "Maria" , "Matthew" , "Michaela" ,
"Paul" , "Sandra" , "William" , "Yilenia" };
//--------------------------- The Code between the dotted lines is the one I still need to write -----------------
char randomnames[16][20];
srand(time(NULL));
for (i = 0; i < 16; i++)
{
j = rand() % 17;
printf("%d\n", j);
randomnames[i] = names[j];
}
//---------------------------------------------------------------------------
for (i = 0; i < 16; i++)
{
puts(randomnames[i]);
}
getchar();
return 0;
}
答案 0 :(得分:1)
拥有
char names[16][20] = ...;
char randomnames[16][20];
你不能做
randomnames[i] = names[j];
但是
char names[16][20] = ...;
char * randomnames[16];
...
randomnames[i] = names[j];
或
char names[16][20] = ...;
char randomnames[16][20];
...
strcpy(randomnames[i], names[j]);
警告,当我看到问题的第一个版本时,您必须打印名称而不是 randomnames ,这意味着您需要修改 randomnames 并且char temp[20]
清楚地表明您必须在随机名称
是这样的:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int i, j, k;
char temp[20];
char names[16][20] = { "Anne" , "Carmen" , "David" , "Jesmond" ,
"John" , "Joseph" , "Karen" , "Kevin" ,
"Manuel" , "Maria" , "Matthew" , "Michaela" ,
"Paul" , "Sandra" , "William" , "Yilenia" };
//--------------------------- The Code between the dotted lines is the one I still need to write -----------------
srand(time(NULL));
for (i = 0; i < 16; i++) /* can be an other number of loop */
{
j = rand() % 17;
k = rand() % 17;
if (j != k) {
strcpy(temp, names[j]);
strcpy(names[j], names[k]);
strcpy(names[k], temp);
}
}
//---------------------------------------------------------------------------
for (i = 0; i < 16; i++)
{
puts(names[i]);
}
getchar();
return 0;
}
如您所见,我使用了所有变量,没有其他变量。
编译和执行示例:
pi@raspberrypi:~ $ gcc -pedantic -Wall s.c
pi@raspberrypi:~ $ ./a.out
Sandra
John
William
Karen
Joseph
Kevin
Manuel
Carmen
Anne
Jesmond
Michaela
Maria
Paul
Matthew
David
Yilenia