代码改变世界

顺序查找

2014-09-13 19:03  星星之火✨🔥  阅读(300)  评论(0编辑  收藏  举报

问题描述:一个结构体数组中存放的是学生的记录,每条记录包括:学号、姓名、成绩。该结构体数组中的内容如下表所示。

 

学生记录

---------------------------------------------

学号 | 姓名 | 成绩

---------------------------------------------

1004 | TOM  | 100

1002 | LILY  | 95

1001 | ANN  | 93

1003 | LUCY | 98

----------------------------------------------

编写一个程序,要求输出1001编号同学的信息。

 

[分析]

首先要定义结构体类型:

typedef struct student

{

  int id;             //学生编号

  char name[10];      //学生姓名

  float score;         //成绩

}Student;

然后初始化结构体数组。为方便起见,这里直接初始化给结构体赋值。在实际的应用中,

记录的获得往往都是从文件中读取的。

接下来采用顺序查找的方法找到1001编号同学的信息。这里的关键字为学生的学号,

因为在学生记录中,只有学号能唯一标识学生的身份,姓名和成绩都不能(因为有重名的情况

和成绩相同的情况)。

 

     程序清单

# include <stdio.h>

 

typedef struct student

{

  int id; //学生编号

  char name[10]; //学生姓名

  float score; //成绩

}Student;

 

int search(Student stu[], int n, int key)

{

  int i;

  for(i=0; i<n; i++)

  {

    if(stu[i].id == key) //查找成功

    return i;

  }

  return -1; //查找失败

}

 

int main(void)

{

  Student stu[4] = { //初始化结构体数组

    {1004, "TOM", 100},

    {1002, "LILY", 95},

    {1001, "ANN", 93},

    {1003, "LUCY", 98},

    };

  int addr; //要查找的记录的地址

  addr = search(stu, 4, 1001);

  printf("Student ID: %d\n", stu[addr].id); //输出查找到的记录的信息

  printf("Student name: %s\n", stu[addr].name);

  printf("Studnet score: %f\n", stu[addr].score);

 

  return 0;

}

 

在vc++6.0中的输出结果是:

Student ID:     1001

Student name:   ANN

Studnet score:  93.000000

Press any key to continue . . .

 

my way is as follows:

# include <stdio.h>

 

typedef struct student

{

  int id;

  char name[10];

  float score;

}Student;

 

int search(Student * stu, int length, int key)

{

  int i;

  for(i=0; i<length; i++)

  {

    if(stu[i].id == key)

    return i;

   }

return -1;

}

 

int main(void)

{

 

  Student stu[4] = {{1004,"TOM", 100}, {1002, "LILY", 95}, {1001, "ANN", 93}, {1003, "LUCY", 98}};

 

  int value = search(stu, 4, 1001);

 

  //查找存在,打印信息

  if(value != -1)

  {

    printf("学号为1001的%s同学的成绩是%f\n", stu[value].name , stu[value].score);

  }

 

  return 0;

}

 

 

在vc++6.0中的输出结果是:

学号为1001的ANN同学的成绩是93.000000

Press any key to continue . . .