21xrx.com
2025-06-17 08:32:51 Tuesday
登录
文章检索 我的文章 写文章
C++中如何判断一个数是否在数组中?
2023-07-14 10:04:13 深夜i     44     0
C++ 判断 数组

在C++中,如果要判断一个数是否在数组中,可以使用循环遍历数组来实现。具体实现步骤如下:

1. 定义一个布尔类型的变量用于存储结果,初始值为false。

2. 使用for循环遍历数组,判断每个数组元素是否等于目标数,如果相等,将布尔类型的变量赋值为true,跳出循环。

3. 判断布尔类型的变量的值,如果为true,则目标数在数组中;反之,则不在数组中。

以下是代码示例:

#include <iostream>
using namespace std;
bool inArray(int target, int arr[], int length) {
  bool result = false; // 初始化结果为false
  for (int i = 0; i < length; i++) {
    if (target == arr[i]) // 判断数组元素是否等于目标数
      result = true; // 若相等
  }
  return result; // 返回结果
}
int main() {
  int target = 3;
  int arr[] = 5;
  int length = sizeof(arr) / sizeof(int); // 计算数组长度
  if (inArray(target, arr, length))
    cout << target << " is in the array." << endl;
   else
    cout << target << " is not in the array." << endl;
  
  return 0;
}

在以上代码中,函数inArray用于判断目标数target是否在数组arr中,length表示数组长度。通过调用inArray函数,可以得知目标数是否存在于数组中。

  
  

评论区