编写c++函数实现在一组数据(1,3,6,4,8,12,9,0,34,23)中查找指定数据,返回数据的指定位置,编号从1开始,如果没有指定数据返回-1
时间: 2024-05-04 07:21:33 浏览: 15
以下是一个简单的C++函数实现,可以在一个数组中查找指定的数据并返回其位置。如果指定的数据不在数组中,则返回-1。
```c++
int findIndex(int arr[], int n, int target) {
// 遍历整个数组
for (int i = 0; i < n; i++) {
// 如果找到了目标数据,返回其位置
if (arr[i] == target) {
return i + 1; // 返回编号从1开始
}
}
// 如果指定数据不在数组中,返回-1
return -1;
}
```
使用方法:
```c++
int main() {
int arr[] = {1, 3, 6, 4, 8, 12, 9, 0, 34, 23};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 8;
int index = findIndex(arr, n, target);
if (index == -1) {
std::cout << "指定数据不在数组中" << std::endl;
} else {
std::cout << "指定数据在数组中的位置为:" << index << std::endl;
}
return 0;
}
```
输出结果:
```
指定数据在数组中的位置为:5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)