C程序-如何检查数组元素

标签 c arrays

<分区>

我有一个函数 repsEqual,它接受一个数组和一个整数,如果数组仅包含出现在相同数字中的相同顺序的数字,则返回 1。否则返回 0。

int repsEqual(int a[], int len, int n)

如果 a{3,2,0,5,3} 并且 n32053 返回1 因为该数组仅包含数字的数字,其顺序与数字中的顺序相同。

如果a{0,3,2,0,5,3}并且n32053 返回 1;我们可以忽略前导零。

我试过这样

int repsEqual(int a[], int len, int n)
{

    int len = sizeof(a)/sizeof(a[0]);
    //storing elements in array
    for(int i=0;i<len;i++)
    {
        scanf("%d", &a[i]); //eg storing:3 2 0 5 3
    }

    //asking user integer number and storing in next array
    scanf("%d",&a2[num]);//eg 32053

}

现在我需要检查 a2 元素的顺序是否与 a1 相同,但不知道如何开始。

最佳答案

这就是你想要的

int repsEqual(int a[], int len, int n)
{
    for (int i = 0; i < len; i++)
    {
        if (a[len - i - 1] == n % 10)
            n /= 10;
        else
            return 0;       
    }

    //For cases where your number-length is longer than your array length
    if (n != 0) return 0; 

    return 1;
}

首先你有你的数组,比如a[5] = { 5, 2, 3, 1, 4}
基本上我所做的是从头到尾循环数组,即 a[len - i - 1]
然后我用 n 的最后一个字符检查它那就是 n%10
因此以 n = 52314 为例,第一个 if 语句 检查是否 (52314 % 10) 是 4 等于 a[4] 也是 4 如果 2 个字符匹配,则循环首先通过删除 n 的最后一个字符继续:52314/10 = 5231。 下一个循环将检查 5231 % 10 和 a[3]
else循环中途中断返回0表示发现不匹配

最后检查完数组中的所有字符,没有发现不匹配,返回1,作为模式匹配

Note: a function should only does what its name says
In your case, check if an array and an integer have the same pattern
User input should be put outside somewhere else, after you have the inputs (the array, the len, and n) you then pass-in to repsEqual for checking

关于C程序-如何检查数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36416638/

相关文章:

javascript - JS - 使用 for 将数组添加到具有变量名称操作的数组

php - 统计每个重复值mysql结果数组

c - C 语言中将变量传递给函数

c - 该结构在 C 内部如何工作?如何将数据从一种结构复制到另一种结构?

c - "thread local storage"和 "thread specific storage"的区别

C编程增加字符串的大小

c - outportb和8086汇编中的out指令有明显区别吗?

c# - 排序数组 C# : key array changes unintendedly

python - 将空数组传递给 sum() 和 product()

php - 如何在不传递数组的情况下使类可以访问数组?