排序查找


注意:如果想用变量来创建数组的个数,必须用malloc函数来申请地址,最后还要free。



在结构体中存放学生信息,每条信息包括:学号,姓名,成绩,按顺序查找学号为1001的学生的具体信息

#include<stdio.h>
#include<iostream>
#include<malloc.h>
using namespace std;

typedef struct student {
    int id;
    char name[10];
    float score;
};

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()
{
    cout << "一个几个学生" << endl;
    int  n;
    cin >> n;
    student* stu;                               //用变量定义数组时要用malloc
    stu = (student*)malloc(sizeof(student)*n);
    for (int i = 1; i <= n; i++)
    {
        cout << "第" << i << "个学生" << endl;
        cout<< "输入:学号,姓名,成绩" << endl;
        cin >> stu[i].id >> stu[i].name >> stu[i].score;
    }
    int result;
    result = search(stu, n, 1001);
    cout << "查询结果是" << endl;
    cout << "学号:" << stu[result].id << endl;
    cout << "姓名:" << stu[result].name << endl;
    cout << "分数:" << stu[result].score<< endl;
    free(stu);
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值