二、简单应用题 请编写一个函数intSeqSearch(intlist[],intstart,intn,intkey),该函数从start开始,在大小为n的数组list中查找key值,返回最先找到的key值的位置,如果没有找到则返回-1。请使用for循环实现。 注意:部分源程序已存在文件kt4_2.cpp中。 请勿修改主函数main和其他函数中的任何内容,仅在函数SeqSearch的花括号中填写若干语句。 文件kt4_2.cpp的内容如下: #include intSeqSearch(intlist[],intstart,intn,intkey) { } voidmain() { intA[10]; intkey,count=0,pos; cout<<"Enteralistof10integers:"; for(pos=0;pos<10;pos++) { cin>>A[pos]; } cout<<"Enterakey:"; cin>>key; pos=0; while((pos=SeqSearch(A,pos,10,key))!=-1) { count++; pos++; } cout< } 【参考答案】 int SeqSearch(int list[], int start, int n, int key) { for(int i=start;i { if(list[i]==key) { return i; } } return -1; } 【试题解析】 本题考查的是考生使用for和if等基本控制结构的综合水平,查找一个数组中的指定元素并返回序号是一个基本操作,注意一维数组的实参格式。
|