c - 测试多个数组中是否存在某些值的最简单方法是什么?

标签 c arrays

我知道这可能看起来像一个硬件问题,并且作为我的客人来对待它,因为这是一个自学练习。

测试多个数组中是否存在特定值的最简单方法是什么?

例如:

伪代码

if array a contains a value of 4 and
   array b contains a value of 2 and
   array c contains a value of 6 
then procede to procedure x

到目前为止我在实现中有什么

#include<stdio.h>

void x(void){/* do stuff */}

int main()
{
    char fndA = 0;
    char fndB = 0;
    char fndC = 0;

    int a[5] = {1,2,3,5,6};    
    int b[5] = {1,2,2,3,4};
    int c[5] = {1,3,4,5,6};

    for(int i=0;i<5;i++)
    {
        if(a[i]==4){fndA=1;}
    }

    //repeat for-loop for b/fndb and c/fndC

    if (fndA && fndB && fndC) {x();}

    return 0;
}

在此示例中,x() 永远不会被调用,因为数组 a 中不存在 4。但是我最终是否必须为每个要测试的数组构建一个 for 循环?谢谢

最佳答案

是的。但是您显然可以创建一个执行循环的函数。您需要将数组、它的大小和您要查找的元素传递给该函数。

int array_contains_int(int *arr, size_t size, int value) {
    int i;
    for(i = 0; i < size; i++)
        if(arr[i] == value)
            return 1;
    return 0;
}

关于c - 测试多个数组中是否存在某些值的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10691807/

相关文章:

c - 将 float 放入二维数组中

c - AVX2 1x mm256i 32 位到 2x mm256i 64 位

c - Eclipse CDT - C 项目

arrays - Google 工作表命名范围多列

c++ - 指向 C 样式数组元素的指针的 const vector

c++ - 复制构造函数不从类对象中获取数组大小

无法理解 sysinfo 返回的负载

android - 如何将控制从字符串委托(delegate)给 C 中的一系列函数

java - 为什么初始化数组后我无法在数组中分配某些值?

javascript - 当我在for中调用javascript函数时,当for循环结束时,返回该函数的所有第i个响应