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; // 返回目标数在数组中的位置 } } &港澳宝典11666comnbsp; 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; }
程序定义了一个函数,通过遍历数组查找目标数的位置。如果找到目标数,则返回其位置;如果未找到,则返回-1。
开奖结果白小姐一肖一码