首页 > 解决方案 > 数组递归

问题描述

最近我被引入了“递归”的概念,这似乎很有趣,直到我遇到一个数组,在该数组中我被要求从用户那里获取一个数组,它的大小并获取数组中的负数和奇数,我已经想到了一些方法来做到这一点,但没有奏效,我尝试用不同的条件或循环来制作它,但每次我发现自己重置负计数器或奇数计数器或只是一个无限循环时,我似乎无法理解如何通过通过这个递归过程的一个数组由于某种原因它一直给我错误的输出所以我重置它并从基本情况开始,在制作递归函数时是否有一种通用的方法可以遵循,我知道它会让你的问题变成较小的子问题并创建基本案例,但我不是无法在这里弄清楚,如果有人可以指导我完成它,将不胜感激。

下面是我为获取数组并将其传递给递归函数的代码,其条件适用于迭代函数,并尝试将基本情况视为if (Count < 0)因为 Count 是数组的大小,所以我考虑从它开始每次我想调用该函数时将其减一,但这似乎也不起作用,有什么想法吗?

提前致谢 !

 #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int SortArray(int* Array, int Size, int* Negative, int* Odd)
{
    if (Size < 0)   
    {
        return;
    }
            if (Array[Size] % 2 == 1 || Array[Size] % 2 == -1)
            {
                return SortArray(*Array, Size - 1, *Negative, *Odd);
            }
            if (Array[Size] < 0)
            {

            }
}
int main()
{
    int Size;
    int Negative = 0;
    int Odd = 0;
    printf("Enter The Size Of The Array: \n");
    scanf("%d", &Size);
    int* Array = malloc(Size * sizeof(int));
    if (Array ==  NULL)
    {
        printf("Malloc Failure ! \n");
        return 0;
    }
    printf("Enter The Elements Of Your Array: \n");
    for (int i = 0; i < Size; i++)
    {
        scanf("%d", &Array[i]);
    }
    SortArray(Array, Size,&Negative,&Odd);
    printf("Odd Count:%d \n", Odd);
    printf("Negative Count:%d \n", Negative);
    free(Array);
    return 0;
}

标签: arrayscrecursion

解决方案


尝试将基本情况视为 (Count < 0),因为 Count 是数组的大小,所以我考虑从它开始,每次我想调用函数时将其减一

这是一个好的开始,函数参数是您想要完成的正确参数。这个名字SortArray有点误导,你没有排序,你在,我认为Count会更合适。也不Size是真正的大小,而是我们的“索引”:

void Count(int *Array, int Index, int *Negative, int *Odd)

基本情况是正确的,我们正在向后扫描数组,所以当Index小于时0,就没有更多的东西了。

现在,您想在再次调用该函数之前更新两个计数器。您的代码中缺少更新部分,这就是您得到错误结果的原因。Count

我会这样做:

int n = Array[Index];       /* current number */
if (n % 2 != 0)             /* is it odd? */
        *Odd += 1;          /* if so, update odd counter by one */
if (n < 0)                  /* is it negative? */
        *Negative += 1;     /* if so, update negative counter by one */

最后,我们再次调用该Count函数减Index一,正如您已经猜到的那样:

Count(Array, Index - 1, Negative, Odd);

放在一起:

void Count(int *Array, int Index, int *Negative, int *Odd)
{
        if (Index < 0)
                return;

        int n = Array[Index];
        if (n % 2 != 0)
                *Odd += 1;
        if (n < 0)
                *Negative += 1;

        Count(Array, Index - 1, Negative, Odd);
}

应该使用最后一个索引第一次调用该函数,并且应该将计数器设置为0(就像您已经做过的那样)。从main()第一次调用将是:

int Negative = 0;
int Odd = 0;
Count(Array, Size - 1, &Negative, &Odd);

你可以制作一个包装函数来“隐藏”这个(重要的)细节。


推荐阅读