线性查找

**

*

从键盘输入某班学生某门课的成绩(每班人数最多不超过40人),当输入为负值时,表示输入结束,试编程从键盘任意输入一个学号,查找该学号学生的成绩。

#include <stdio.h>
#include <stdlib.h>
#define N 40
int ReadScore(int score[],long num[]);//ReadScore()函数原型
int LineSearch(long num[],long x, int n);//LineSearch()函数原型
int main()

{
int score[N],n,pos;
long num[N],x;
n=ReadScore(score,num);//输入成绩和学号,返回学生总数
printf(“Total students are %d\n”,n);
printf(“Input the searching ID:”);
scanf("%ld",&x);//以长整型格式从键盘输入待查找的学号
pos=LinSearch(num,x,n);//查找学号为num的学生
if(pos!=-1)//若找到,则打印其分数
printf(“score=%d\n”,score[pos]);
else//若未找到,则打印“未找到”提示信息
printf(“Not found!\n”);
return 0;
}//函数功能:输入学生的学号及其门课成绩,当输入为负值时,结束输入,返回学生人数
int ReadScore(int score[],long num[])//ReadScore()函数定义
{
int i=-1;//i初始化为-1,循环体内增1后可保证数组下标从0开始
do{
i++;
printf(“Input student’s ID and score:”);
scanf("%ld%d",&num[i],&score[i]);
}while(num[i]>0&&score[i]>=0);//输入负值时结束成绩输
return i;//返回学生总数
}//按线性查找值为x的数组元素,若找到则返回x在数组中的下标位置,否则返回-1

int LinSearch(long num[],long x,int n)//LinSearch()函数定义
{
int i;
for(i=0;i<=n;i++)
{
if(num[i]==x) return i;//若找到则返回x在数组中的下标
}
return -1;//若循环结束仍未找到,则返回-1;
}

程序的测 试结果如下


Input student’s ID and score:120310122 84
Input student’s ID and score:120310123 83
Input student’s ID and score:120310124 88
Input student’s ID and score:120310125 87
Input student’s ID and score:120310126 61
Input student’s ID and score:-1-1
Total students are 5
Input the searching ID:120310123
score=83

Process returned 0 (0x0) execution time : 202.086 s
Press any key to continue.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值