Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
该代码可以返回目标编号的位置。但是,如果目标编号不在数组中,则程序应返回-1。还要求我仅使用递归。

这是代码:

#include <stdio.h>

int rLookupAr(int ar[], int n, int target);

int main() {
    int a[80];
    int target, i, size;

    printf("Enter array size: ");
    scanf("%d", &size);
    printf("Enter %d numbers: ", size);
    for (i = 0; i < size; i++)
        scanf("%d", &a[i]);
    printf("Enter target number: ");
    scanf("%d", &target);
    printf("rLookupAr(): %d", rLookupAr(a, size, target));
    return 0;
}

int rLookupAr(int ar[], int n, int target) {
    /* write your code here */
    if (ar[0] == target) {
        if (n == 0)
            return -1;
        else
            return 0;
    } else
        return 1 + rLookupAr(ar + 1, n - 1, target);
}

最佳答案

该功能可以看起来像

int rLookupAr( const int ar[], int n, int target )
{
    if ( n < 1 )
    {
        return -1;
    }
    else if ( ar[0] == target )
    {
        return 0;
    }
    else
    {
        int i = rLookupAr( ar + 1, n - 1, target );
        return i == - 1 ? i : i + 1;
    }
}

09-20 00:57