迷失在递归中 - 如何反转打印用户输入单个字符并将它们相乘

时间:2014-03-21 08:11:05

标签: c recursion

抱歉模糊,但我只是无助,坐了4个小时:|

#include <stdio.h>

int temp (int count)
{
    int j = 0;
    char c;
    printf("Enter a char\n");
    do
    {
        c = getchar();
    }
    while(c=='\n');
    if (c == 'x')
        return;
    temp(count+1);
    for (j=0;j <count+1;j++)
    putchar(c);
    printf("\n");
    return count;
}


int print_in_reverse()
{
    int count = 0;
    temp(0);
    printf("%d\n" , count);

}

我在流泪和痛苦中,需要扭转它。

1 个答案:

答案 0 :(得分:1)

你是如此接近目标。如果将count作为参数传递,则会在更深的递归时获得更大的值。将其移至返回值,以便在更深的递归时获得更小的值。

#include <stdio.h>

int temp ()
{
    int j = 0;
    int count;
    char c;
    printf("Enter a char\n");
    do
    {
        c = getchar();
    }
    while(c=='\n');
    if (c == 'x')
        return 0;
    count = temp(); /* Recursive call. */
    for (j=0;j <count+1;j++)
        putchar(c);
    printf("\n");
    return count+1; /* Return an increased count. */
}

int print_in_reverse()
{
    int count = 0;
    count = temp();
    printf("%d\n" , count);

}