在C中使用递归查找之间的数字 [英] Find the number in between using recursive in C

查看:92
本文介绍了在C中使用递归查找之间的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个函数来查找使用递归之间的数字

create a function to find the number in between using recursion

int within(int a[], int N, int lower, int upper, int result[])

输入:

int a [] = {4,1,3,1,3,2};



输出范围在2到3之间:

{3,3,2},计数= 3



我有什么试过:



Input:
int a[] = {4, 1, 3, 1, 3, 2};

Output range between 2 to 3:
{3,3,2}, count = 3

What I have tried:

int within(int a[], int N, int lower, int upper, int result[])
{
    int count = 0;
    if (N == 1 && a[0] >= lower && a[0] <= upper) return a[0]; // base case
    for(int i = 0; i < N - 1; i ++){
        if (a[i] >= lower && a[i] <= upper){
            return within(&a[0], N - 1, lower, upper,result);
            count++;
        }
        return count;
    }
}

推荐答案

return within(&a[0], N - 1, lower, upper,result);
count++; // this will never be executed, as it follows a return statement


编译器可能会抱怨'所有路径都没有返回'

the compiler probably complain that 'all path do not have a return'
int within(int a[], int N, int lower, int upper, int result[])
{
    int count = 0;
    if (N == 1 && a[0] >= lower && a[0] <= upper) return a[0]; // base case
    for(int i = 0; i < N - 1; i ++){
        if (a[i] >= lower && a[i] <= upper){
            return within(&a[0], N - 1, lower, upper,result);
            count++;
        }
        return count;
    }
    // because a return is missing here
}



你的要求对我没用。我不知道如何使用示例输入获得4作为输出。

您的代码对我来说也没有意义。我没有看到它的逻辑。


your requirement make no sense to me. I don't see how you can get 4 as output with the sample input.
Your code also make no sense to me. I don't see its logic.


这篇关于在C中使用递归查找之间的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆