排序查找
2016-04-12 14:50
302 查看
注意:如果想用变量来创建数组的个数,必须用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;
}
在结构体中存放学生信息,每条信息包括:学号,姓名,成绩,按顺序查找学号为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;
}
相关文章推荐
- js一百零一夜之第十五夜正则表达式(2)
- 正则表达式
- c#压缩和解压缩
- MySQL内存表-临时表
- 数据库设计Step by Step (9)——ER-to-SQL转化
- SVN命令行的使用
- java多线程那些事之并发集合
- Unity 人物如何跟随鼠标转向 ScreenPointToRay RaycastHit Raycast transform.LookAt
- OpenGL基础图形编程(九)OpenGL颜色
- java 关于初学面向对象的问题一:对象的三大特性
- java.sql.Date 与 java.util.Date 的转换
- 【poj 3461】 Oulipo 中文题意&题解&代码(C++)
- Android存储登陆信息
- Mini-KMS_Activator激活office2010使用教程
- Linux下安装Git
- POJ3268 Silver Cow Party(最短路径)
- Android:6.0运行时权限解析
- 【BZOJ 1641】【Usaco2007 Nov】Cow Hurdles 奶牛跨栏(最短路变形)
- 进程间通信-命名管道FIFO
- iOS二维码扫描,你需要注意的两件事