参考:C语言程序设计,P112
// excise_20230815a.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//查找数组
#include <iostream>
#include <stdio.h>
using namespace std;
#define SIZE 10
int find(int a[], int n, int x); //查找数组
int main()
{
int array[SIZE], i = 0, n, x;
int pos;
do {
printf("请输入数组长度n:(1<n<%d):", SIZE);
scanf_s("%d", &n);
} while (n<1 || n>SIZE);
printf("请输入%d 个元素:", n);
for (i = 0; i < n; i++)
{
scanf_s("%d", &array[i]); //输入数组元素
}
printf("请输入查找的值x\n");
scanf_s("%d", &x);
pos = find(array, n, x); //输入参数:数组名,数组长度,查找的数
if (pos < n)
{
printf("值等于%d, 索引为%d\n", x, pos);
}
std::cout << "Hello World!\n";
}
//函数功能:完成一维数组的查找
//函数参数:3个形式参数分别对应于待查找的数组、数组的有效元素个数
// 以及待查找的值
//函数返回值:返回查询结果,成功时返回元素下标,不成功是返回数组长度值
int find(int a[], int n, int x) //查找数组
{
int i = 0;
while (i < n)
{
if (x == a[i])
break;
i++;
}
return i;
}
运行结果: