美文网首页
【MAC 上学习 C++】Day 49-4. 实验8-1-5 在

【MAC 上学习 C++】Day 49-4. 实验8-1-5 在

作者: RaRasa | 来源:发表于2019-10-12 20:30 被阅读0次

实验8-1-5 在数组中查找指定元素 (15 分)

1. 题目摘自

https://pintia.cn/problem-sets/13/problems/548

2. 题目内容

本题要求实现一个在数组中查找指定元素的简单函数。

函数接口定义:

int search( int list[], int n, int x );
其中list[]是用户传入的数组;n(≥0)是list[]中元素的个数;x是待查找的元素。如果找到

则函数search返回相应元素的最小下标(下标从0开始),否则返回−1。

输入样例1:

5
1 2 2 5 4
2

输出样例1:

index = 1

输入样例2:

5
1 2 2 5 4
0

输出样例2:

Not found

3. 源码参考
#include <iostream>

using namespace std;

#define MAXN 10

int search( int list[], int n, int x );

int main()
{
    int i, index, n, x;
    int a[MAXN];

    cin >> n;

    for( i = 0; i < n; i++ )
    {
      cin >> a[i];
    }

    cin >> x;

    index = search( a, n, x );
    if( index != -1 )
    {
      cout << "index = " << index << endl;
    }
    else
    {
      cout << "Not found" << endl;
    }
  
    return 0;
}

int search( int list[], int n, int x )
{
  for(int i = 0; i < n; i++)
  {
    if(list[i] == x)
    {
      return i;
    }
  }

  return -1;
}

相关文章

网友评论

      本文标题:【MAC 上学习 C++】Day 49-4. 实验8-1-5 在

      本文链接:https://www.haomeiwen.com/subject/vhsgectx.html