gpt4 book ai didi

c - 制作一个初学者 C 程序来根据年龄读取和排序学生

转载 作者:行者123 更新时间:2023-11-30 17:38:28 26 4
gpt4 key购买 nike

代码:

    #include <stdio.h>

typedef struct person {
int age ;
char name[40];
}person;

void perm ( person * A , person * B ){
person temp ;
temp = *A ;
*A = *B ;
*B = temp ;
}

void main () {
person classroom[6];
int i , j ;
// reading students name and ages
for ( i=0 ; i<6 ; i++ ){
printf("Enter name :");
fgets (classroom[i].name, 40, stdin);
printf("Enter age : ");
scanf("%d",&classroom[i].age);
}
// sorting them
for ( i=0 ; i<6 ; i++ ){
for ( j=0 ; j<6-i ; j++ ){
if ( classroom[j].age > classroom[j+1].age ){
perm (&classroom[j],&classroom[j+1]);
}
}
}
// printing them sorted
printf("\n After sorting accoring to ages :");
for ( i=0 ; i<6 ; i++ ){
printf(" %s \n",classroom[i].name[40]);
}
// finished
getchar();
getchar();

}

该程序应该:

  1. 定义学生类型“person”。
  2. 定义两人交换过程“void perm (person * A, person * B);”。
  3. 声明一组名为“classroom”的人员。
  4. 填充数组名称和年龄。
  5. 使用冒泡排序算法进行排序。
  6. 显示排序后的数组。

最佳答案

我快速检查了一下,发现该代码中至少有 3 个主要错误:

1) 当你查找学生姓名时,你会遇到麻烦,因为 scanf 中没有正确处理 '\n',要正确处理它,你需要使用 '\n',例如你可以添加getc() 直接在 scanf 之后,就像我在下面的代码片段中所做的那样:

 for ( i=0 ; i<6 ; i++ ){
printf("Enter name :");
fgets (classroom[i].name, 40, stdin);
printf("Enter age : ");
scanf("%d",&classroom[i].age);
/* Add this one will catch the \n for you making the code working better */
getc(stdin); /* <<<<< ADD THIS LINE */
}

2)这里存在缓冲区溢出:

 for ( j=0 ; j<6-i ; j++ ){
if ( classroom[j].age > classroom[j+1].age ){
perm (&classroom[j],&classroom[j+1]);
}
}

当 i=0, j=5 =>classroom[j+1]==>classroom[6] 且索引 6 时,它位于边界之外。您需要将循环设置为最多 5

for ( j=0 ; j<5-i ; j++ ){
if ( classroom[j].age > classroom[j+1].age ){
perm (&classroom[j],&classroom[j+1]);
}
}

3) 当您打印结果时,您指向的位置超出了字符串的末尾。此外,您没有指向字符串,但尝试获取为名称保留的空间之外的第一个字符,因为您错过了符号“&”,而不是:

printf(" %s \n",classroom[i].name[40]);

您必须使用以下内容:

printf(" %s \n", &classroom[i].name[0]);

关于c - 制作一个初学者 C 程序来根据年龄读取和排序学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com