咨诹

来源:互联网 发布:网络彩票重启 编辑:程序博客网 时间:2024/04/29 12:45

郭老师您好,最近在复习C语言时,自己用选择和冒泡排序写了两个函数,用来给一个结构数组进行排序。操作过程中有一些疑问不太能够搞懂,想咨询一下,麻烦郭老师了,谢谢。


首先,自己的编写的代码如下:

#include <stdio.h>#define n 5struct s_type{    int num;    char name[10];    float score;} student[n];void function_x(struct s_type *a){    int i,j,pos;    struct s_type temp;    for(i=0;i<n;i++)    {        pos=i;        for(j=i+1;j<n;j++)        {            if((a+j)->score>(a+pos)->score)            {                pos=j;            }        }        temp=*(a+i);        *(a+i)=*(a+pos);        *(a+pos)=temp;    }}void function_m(struct s_type *a){    int i,j;    struct s_type temp;    for(i=0;i<n;i++)    {        for(j=1;j<n-i;j++)        {            if((a+j-1)->score<(a+j)->score)            {                temp=*(a+j-1);                *(a+j-1)=*(a+j);                *(a+j)=temp;            }        }    }}void main(){    for(int k=0;k<n;k++){scanf("%d,%s,%f",&student[k].num,&student[k].name,&student[k].score);}    /*struct s_type student[n]={        {501,"zhang",85.5},        {502,"tian",80},        {503,"wang",68},        {504,"chen",77},        {505,"xu",93}};*/    function_x(student);    for(int r=0;r<n;r++)    {    printf("%d,%s,%f",student[r].num,student[r].name,student[r].score);        printf("\n");    }}

疑问如下:

  1. 在该段代码中,我在main函数中注释掉了一段,如果去掉注释,删去通过for循环来初始化结构数组的那一段代码,可以证明,选择与冒泡的排序是正确的。但是,如果通过for循环来初始化结构数组,手动输入后,结果有异常。VC运行结果如下:

运行结果

从图片中的显示来看,似乎原样输出了结构数组,没有任何处理。同时,运行结果在每行多了一个尾巴。不清楚是代码的哪一部分出错,恳请老师指导。谢谢。

0 0
原创粉丝点击