2 fengrhan FengRHan 于 2014.12.05 22:36 提问

C语言STRUCT数组 不知道哪错了

#include
int main(void)
{
int i,j;
float temp;
struct Students
{
char num;
char name;
char sex;
char age;
float score;
};
struct Students student[5]=
{
{'0001','一号','男','19',99},
{'0002','二号','女','18',96},
{'0003','三号','女','19',93},
{'0004','四号','男','20',97},
{'0005','五号','男','7',100}
};
for(i=0;i<5;i++)//按成绩排序//
{
for(j=0;j<5-i;j++)
{
if(student[j].score<student[j+1].score)
{
temp=student[j].score;
student[j].score=student[j+1].score;
student[j+1].score=temp;
}
}
}
for(i=0;i<5;i++)
{
printf("%8s",student[i].num);
printf("%12s",student[i].name);
printf("%6s",student[i].sex);
printf("%s",student[i].age);
printf("%d\n",student[i].score);

}
return 0;

}

7个回答

mingwanlau
mingwanlau   2014.12.05 23:21

'0001','一号','男' 是char型吗?
struct Students
{
char *num;
char *name;
char *sex;
char *age;
float score;
};
struct Students student[5]=
{
{"0001","一号","男","19",99},
{"0002","二号","女","18",96},
{"0003","三号","女","19",93},
{"0004","四号","男","20",97},
{"0005","五号","男","7",100}
};

sungaochao
sungaochao   2014.12.05 23:24

只是对成绩进行了排序,结构体的其他部分没有改变顺序。

u013704361
u013704361   2014.12.06 00:02

'0001','一号','男','19' 的数据类型有问题

eagleyan
eagleyan   Rxr 2014.12.06 00:25

你这里只是把成绩排序了,而不是按程序排序
你最后的结果是
'0001','一号','男','19',93
'0002','二号','女','18',96,
'0003','三号','女','19',97,
'0004','四号','男','20',99,
'0005','五号','男','7',100
而不是你预想的排序,排序是交换数组里的学生啊。
另外,你的程序有bug,你的
for(i=0;i<5;i++)//按成绩排序//
{
for(j=0;j<5-i;j++)
if(student[j].score<student[j+1].score)
当i=0, j = [0~4], j + 1= 5,数组越界了,很惊诧居然你的程序完整的run完了,也许当时内存里面的结构在下个位置有一个满足条件的score,但是很诡异,这个数组越界是一个明显的bug

xuzuning
xuzuning   Ds   Rxr 2014.12.06 09:38

错误太多,不一一列举。请对比正确的代码

int main(void) {
  int i,j;
  struct Students {
    char *num;
    char *name;
    char *sex;
    char *age;
    float score;
  }student[5] = {
   {"0001","一号","男","19",99},
   {"0002","二号","女","18",96},
   {"0003","三号","女","19",93},
   {"0004","四号","男","20",97},
   {"0005","五号","男","7",100}
  };
  struct Students temp;

  /* 按成绩排序 */
  for(i=0;i<5;i++) {
    for(j=0;j<5-i;j++) {
      if(student[j].score<student[j+1].score) {
        temp = student[j];
        student[j] = student[j+1];
        student[j+1] = temp;
      }
    }
  }
  for(i=0;i<5;i++) {
    printf("%8s",student[i].num);
    printf("%12s",student[i].name);
    printf("%6s",student[i].sex);
    printf("%s",student[i].age);
    printf("%d\n",student[i].score);
  }
  return 0;
} 
u013678862
u013678862   2014.12.06 11:06

你把main函数写在结构体后面试试

wangyaninglm
wangyaninglm   Ds   Rxr 2015.01.02 17:13

错误还是挺多的,你首先结构体都在主函数前没有声明

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!