zoukankan      html  css  js  c++  java
  • 数据结构C语言实现----顺序查找

     建立上图的一个txt文件:

    1004 TOM 100
    1002 lily 95
    1001 ann 93
    1003 lucy 98

    用一个c程序读入这个表一个结构体数组中:

    结构体如下:

    //学生数据结构体
    typedef struct student
    {
        int id;        //学号
        char name[10];      //姓名
        int score;      //成绩
    } Student;
    

      

    以学号为关键字,查找学生成绩

    运行示例:

    代码如下:

    /*********************************
     * 顺序查找
     * 从文件读取一组数据
     * 存入到结构体中
     * 对比key查找
     * *******************************/
    #include<stdio.h>
    #include<stdlib.h>
    //学生数据结构体
    typedef struct student
    {
        int id;        //学号
        char name[10];      //姓名
        int score;      //成绩
    } Student;
    //函数声明
    int sq_search(Student r[] , int n , int key);//顺序查找
    
    
    
    int main(int argc , char *argv[])
    {
        Student r[4];
        FILE *fp;
        //判断命令行是否正确输入
        if (argc!=2)
        {
            printf("命令行输入错误!");
            return 0;
        }
        //判断文件是否成功打开
        if ((fp = fopen(argv[1] , "r")) == NULL)
        {
            printf("文件打开失败!");
            return 0;
        }
        //从文件中读取数据信息
        for (size_t i = 0; i < 4; i++)
        {
            fscanf(fp , "%d %s %d",&(r[i].id),&(r[i].name),&(r[i].score));
        }
        //顺序查找
        int key,i;
        while (1)
        {
            printf("请输入要查找的学生的学号:");
            scanf("%d",&key);
            i = sq_search(r,4,key);
            if (i!=-1)
            {
                printf("学号:%d
    姓名:%s
    成绩:%d
    ",r[i].id,r[i].name,r[i].score);
            }else
            {
                printf("列表中没有该学生的信息!");
            }
        }
        
        return 0;
    }
    //顺序查找
    int sq_search(Student r[] , int count , int key)
    {
        for (size_t i = 0; i < count; i++)
        {
            if (r[i].id==key)
            {
                return i;
            }
        }
        return -1;
    }
    

      

  • 相关阅读:
    React Native ios打包
    ReactNative state更新,视图不更新的问题
    XF警告试图
    XF 彩色矩形块
    XF 定制图片
    XF 通过判断平台加载不同的图片
    XF 进度条和指示器
    XF 滑块和步进控件
    XF 开关控件
    XF 按钮控件
  • 原文地址:https://www.cnblogs.com/jerryleesir/p/13392424.html
Copyright © 2011-2022 走看看