C语言 递归函数,用于在两个数组之间的相同位置上查找相同的数字



下面是结果应该是什么的示例:

1234 和 1344 在同一位置有两个数字。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Proverka(int *num1[], int *num2[], int len, int pom) 
{   
    if (len < 1 && pom < 1)
        return 0;
    if (*num1 == *num2)
        return 1 + Proverka(num1++, num2++, len-1, pom-1);
    else {
        return Proverka(num1++, num2++, len-1, pom-1);
    }
}
int main (void)
{
    int *num1[5], *num2[5], pom, len, i, sin, j;
    pom = sizeof(num1) / sizeof(num1[0]);
    len = sizeof(num2) / sizeof(num2[0]);
    for (i = 0; i < pom; i++) {
        printf("Enter elements for first array :");
        scanf("%d", num1[i]);
    }
    for (j = 0; j < len; j++){
        printf("Enter elements for second array : ");
        scanf("%d", num2[j]);
    }
    sin = Proverka(num1, num2, pom, len);
    {
        printf("They have %d numbers on same positions", sin);
    }   
    return 0;
}

代码中有很多错误,这是它的工作版本。

阅读评论以了解我更改的内容。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Proverka(int *num1, int *num2, int len1, int len2)
{
    if (len1 < 1 && len2 < 1) return 0;
    // note the pre-increment. Your post-increment wouldn't have worked. Or just add 1.
    return (*num1 == *num2) + Proverka(++num1, ++num2, len1 - 1, len2 - 1);
    // this works, since "boolean" is really just 0 or 1
}
int main (void)
{
    // I make array of ints, not of pointers to ints.
    int num1[5], num2[5], len1, len2, i, same;
    len1 = sizeof(num1) / sizeof(num1[0]);
    len2 = sizeof(num2) / sizeof(num2[0]);
    for (i = 0; i < len1; i++) {
        printf("First array element %d:", i+1);
        scanf("%d", &num1[i]); // pointer at the element
    }
    for (i = 0; i < len2; i++){
        printf("Second array element %d:", i+1);
        scanf("%d", &num2[i]);
    }
    // get pointers at the first array elements
    same = Proverka(&num1[0], &num2[0], len1, len2);
    printf("They have %d numbers on same positionsn", same); // newline - good practice
    return 0;
}

这里有一个更"优化"和清理的版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ITEMS 5
int Proverka(const int *aa, const int *bb, const int len)
{
    if (len == 0) return 0;
    return (*aa == *bb) + Proverka(1 + aa, 1 + bb, len - 1);
}
int main (void)
{
    int aa[ITEMS], bb[ITEMS], i, same;
    for (i = 0; i < ITEMS; i++) {
        printf("First array element %d:", i+1);
        scanf("%d", &aa[i]);
    }
    for (i = 0; i < ITEMS; i++) {
        printf("Second array element %d:", i+1);
        scanf("%d", &bb[i]);
    }
    same = Proverka(&aa[0], &bb[0], ITEMS);
    printf("They have %d numbers on same positionsn", same);
    return 0;
}

为此使用递归不是一个非常好的选择,循环会更容易、更安全。但这也适用于不太大的数组。

int *num1[5],*num2[5] ...不会为您提供分配了内存的整数指针数组。修复它。使用 malloc 分配内存。

或者只是说int num1[5],num2[5]scanf("%d",&num1[i]);

最新更新