请编写一个函数int SeqSearch(int list[],int start,int n,int key),该函数从start开始,在大小为n的数细list中查找key值,返回最先找到的key值的位置,如果没有找到则返回-1。请使用for循环实现。

admin2009-01-15  74

问题 请编写一个函数int SeqSearch(int list[],int start,int n,int key),该函数从start开始,在大小为n的数细list中查找key值,返回最先找到的key值的位置,如果没有找到则返回-1。请使用for循环实现。
   注意:部分源程序已存在文件test19_2.cpp中。
   请勿修改主函数main和其他函数中的任何内容,仅在函数SeqSearch的花括号中填写若干语句。
   文件test19_2.cpp的内容如下:
      #include <iostream.h>
      int SeqSearch(int list[],  int start,  int n,  int key)
      {
      }
      void main()
      {
       int A[10];
       int key, count=0, pos;
       cout<<"Enter a list of 10 integers:  ";
       for(pos=0;pos<10;pos++)
       {
         cin>>A[pos];
       }
       cout<<"Enter a key:  ";
       cin>>key;
       pos=0;
       while( (pos=SeqSearch(A, pos,10,key))!=-1)
       {
           count++;
           pos++;
       }
       cout<<key<<" occurs "<<count<<(count!=1?" times":" time")<<" in the list."<<end1;
       }

选项

答案int SeqSearch(int list[], int start, int n,int key) { for(int i=start;i<n;i++) { if(list[i]==key) { return i; } } return -1; }

解析 本题考查的是考生使用for和if等基本控制结构的综合水平,查找一个数组中的指定元素并返回序号是一个基本操作,注意一维数组的实参格式。
转载请注明原文地址:https://kaotiyun.com/show/HOID777K
0

最新回复(0)