c++求一个数在数组中出现的位置
作者:野牛程序员:2024-06-30 11:19:30 C++阅读 2629
c++求一个数在数组中出现的位置
c++求一个数在数组中出现的位置
#include <iostream> using namespace std; int findPosition(int arr[], int size, int target) { for (int i = 0; i < size; i++) { if (arr[i] == target) { return i; // 返回目标数在数组中的位置 } } return -1; // 如果未找到目标数,返回-1 } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); int target = 3; int position = findPosition(arr, size, target); if (position != -1) { cout << "目标数 " << target << " 在数组中的位置是: " << position << endl; } else { cout << "目标数 " << target << " 不在数组中" << endl; } return 0; }
程序定义了一个findPosition
函数,通过遍历数组查找目标数的位置。如果找到目标数,则返回其位置;如果未找到,则返回-1。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++判断数组为空
- 下一篇:arduino如何调节连续电压