阅读以下说明和C++代码,将解答写入对应栏内。 【说明】 请编写一个函数int SeqSearch(int list[],int start,int n,int key),该函数从start开始,在大小为n的数组list中查找key值,返回最先找到的

admin2012-12-10  27

问题 阅读以下说明和C++代码,将解答写入对应栏内。
【说明】
   请编写一个函数int SeqSearch(int list[],int start,int n,int key),该函数从start开始,在大小为n的数组list中查找key值,返回最先找到的key值的位置,如果没有找到则返回-1。请修改程序中画线部分的错误并将不同情况下的输出结果补充完整。
   【程序】
   文件search.cpp的内容如下:
   #include <iostream. h >
   int SeqSearch( int list[ ] ,int start,int n,int key)
   {
       for(int i=start;i<=n;i++) //(1)
           {
               if( list = key)//(2)
               {
                 return i;
               }
           }
           return -1;
   }
   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; //(3)
       }
       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,"
       << endl;
   }
   第一种情况:输入2 3 12 6 8 45 8 33 7输入key:8
   输出:(4)  
   第二种情况:输入2 3 126 8 45 8 33 7输入k6y:9
   输出:(5)   

选项

答案(1)for(int i=start;i<n;i++) (2)if(list[i]==key) (3)cin>>A[pos] (4)8 occurs 2 times in the list (5)9 occurs 0 time in the list

解析 数组下标从0开始,所以n次循环要在i=n-1时结束,而不是在i=n时结束。判断是否相等使用“==”,一个等号是赋值。将输入数字逐个赋给A的pos处的元素。8出现2次,注意结果中的 times。9出现0次,注意结果中的time。
转载请注明原文地址:https://kaotiyun.com/show/76jZ777K
0

相关试题推荐
随机试题
最新回复(0)