结构体例题输出函数小问题

问题1:格式符对应不正确造成输出有问题

void showStudentsInformation(struct STI *s, int Cnt)
{
    int i;

    printf("当前学生信息共%d人,信息分别如下:\n", Cnt);
    printf("学号  姓名  性别  年纪  分数\n");

    for(i = 0; i < Cnt; i++)
    {
        printf("%s %s %s %d %lf\n", s[i].id, s[i].name, (s[i].sex == 'm' ? "男" : "女"), s[i].age, s[i].score);  //正确步骤
        //printf("%s %s %s %d %lf\n", s[i].id, s[i].name, s[i].sex , s[i].age, s[i].score);  
        // 刚开始程序为 printf("%s %s %s %d %lf\n", s[i].id, s[i].name, s[i].sex , s[i].age, s[i].score);  到了这一步就卡住了
        // 原因:分析函数可知,s[i].sex 存入的值为'f'/'m',但是结构体声明中的s[i].sex为int型,故执行到这就卡住了
    }
}

void main(void)
{
    struct STI st[20];   //st表示student,st的数据类型为struct STI,此处假设有20个学生
    int stCount = 0;
    inputStudentsInformation(st, &stCount);  //st <=> &st[0] 
    showStudentsInformation(st, stCount);
}

结果如下:

问题2:输出对不齐

void showStudentsInformation(struct STI *s, int Cnt)
{
    int i;

    printf("\n当前学生信息共%d人,信息分别如下:\n", Cnt);
    //printf("学号  姓名  性别  年纪  分数\n");                             //对不齐形式 

    printf("%8s %20s %4s %4s %4s\n", "学号",  "姓名", "性别", "年纪", "分数");  //对齐形式
 

    for(i = 0; i < Cnt; i++)
    {
        //printf("%s %s %s %d %lf\n", s[i].id, s[i].name, (s[i].sex == 'm' ? "男" : "女"), s[i].age, s[i].score);     //对不齐形式

        printf("%8s %20s %4s %4d %.1lf\n", s[i].id, s[i].name, (s[i].sex == 'm' ? "男" : "女"), s[i].age, s[i].score);  //对齐形式
  }
}

void main(void)
{
    struct STI st[20];   //st表示student,st的数据类型为struct STI,此处假设有20个学生
    int stCount = 0;
    inputStudentsInformation(st, &stCount);  //st <=> &st[0] 
    showStudentsInformation(st, stCount);
}

输出结果如下:

问题3:自己思路和老师思路不同出现的问题

void showStudentsInformation(struct STI *s, int Cnt)
{
    int i;

    printf("\n当前学生信息共%d人,信息分别如下:\n", Cnt);    
    printf("%8s %20s %4s %4s %4s\n", "学号",  "姓名", "性别", "年纪", "分数");  //对齐形式
    
    for(i = 0; i < Cnt; i++)
    {
        printf("%8s %20s %4s %4d %.1lf\n", (s+i)->id, (s+i)->name, ((s+i)->sex == 'm' ? "男" : "女"), (s+i)->age, (s+i)->score);   //自己方法正确形式

        //printf("%8s %20s %4s %4d %.1lf\n", s[i].id, s[i].name, (s[i].sex == 'm' ? "男" : "女"), s[i].age, s[i].score);  //老师正确形式
        //printf("%8s %20s %4s %4d %.1lf\n", s->id, s->name, (s->sex == 'm' ? "男" : "女"), s->age, s->score);    //自己方法错误形式
        //*s = s[i++];

        //错误原因:指针一直指向同一个数组,故输出只能是同一个数组,没有进行指针的移位

        //和老师方法的区别:老师是用数组表示的,而自己是用指针方式表示的
    }
}

void main(void)
{
    struct STI st[20];   //st表示student,st的数据类型为struct STI,此处假设有20个学生
    int stCount = 0;
    inputStudentsInformation(st, &stCount);  //st <=> &st[0] 
    showStudentsInformation(st, stCount);
}

               

猜你喜欢

转载自blog.csdn.net/weixin_42072280/article/details/82634114