计数直到一定数量向下递归

时间:2019-10-17 14:56:01

标签: c function recursion countdown definition

这是C分配。使用void countDownUp(unsigned int k)编写递归进行计数,直到递减一定数量,然后立即备份。例如,如果为k = 3,则输出应为3 2 1 0 1 2 3。我已经写了一个countDown函数

void countDown(unsigned int k)
{   
    printf("%d ", k);
    if (k > 0)
        countDown(k-1);
}

,还有一个countUp函数。我在void countDownUp(unsigned int k)函数中使用了以下函数:

void countDownUp(unsigned int k)
{   
    countDown(k);
    static int n=0;
    if(n < k){
        printf("%d ", n+1);
        n++;
        countDownUp(k);
    }
}

现在的输出为3 2 1 0 1 3 2 1 0 2 3 2 1 0 3 3 2 1 0,我知道它不起作用,但是我不知道如何调整到正确的输出。有人可以给我一些建议吗?非常感谢你!

2 个答案:

答案 0 :(得分:1)

不需要使用静态变量。该函数可以写得更简单。

#include <stdio.h>

void countDownUp( unsigned int n )
{
    printf( "%u ", n );
    if ( n )
    {
        countDownUp( n - 1 );
        printf( "%u ", n );
    }       
}

int main(void) 
{
    countDownUp( 3 );

    return 0;
}

程序输出为

3 2 1 0 1 2 3

关于您的函数实现

void countDownUp(unsigned int k)
{   
    countDown(k);
    static int n=0;
    if(n < k){
        printf("%d ", n+1);
        n++;
        countDownUp(k);
    }
}

然后在函数内调用

countDownUp(k);

重新调用countDown(k);,其值与传递给函数k的当前调用的countDownUp相同,因为在函数内k的值没有改变..

此外,您还需要指定转换说明符%u而不是%d,因为变量k的类型为unsigned int

答案 1 :(得分:0)

问:CountDownUp()在一般情况下会做什么?
答:它打印n次两次,结果之间为CountDownUp(n - 1)

void CountDownUp(int n) {
    printf("%d ", n);
    CountDownUp(n - 1);
    printf("%d ", n);
}

问:停止条件是什么?
答:以0调用CountDownUp时。
问:那我们该怎么办?
答:仅打印一次并停止递归。

void CountDownUp(int n) {
    printf("%d ", n);
    if (n == 0) return;
    CountDownUp(n - 1);
    printf("%d ", n);
}

Voila!