计数直到递减一定数量然后递归备份

问题描述 投票:0回答:1

这是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,我知道它不起作用,但是我不知道如何调整到正确的输出。有人可以给我一些建议吗?非常感谢!

c count countdown
1个回答
0
投票

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

#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);

© www.soinside.com 2019 - 2024. All rights reserved.