0

I understand that this is a very trivial problem.

I am trying to write a program that will keep asking for user input as an int until the user enters 0 at which point it will terminate and print out all the digits in reverse. This is what I have so far:

int revList(int num)
{
    if (num != 0)
    {
        scanf("%d", &num);
        printf("%d\n", revList(num));
        return num;
    }
    return 0;
}

with my main method being:

int revList(int);

printf("%d", revList(1));

the 1 in the revList was chosen arbitrarily to satisfy the compiler's need for an arguement even though it's useless in the first iteration.

I understand that my code is probably inefficient and not making use of recursion properly.

The code works but has 1 problem: it prints 0 two times and then the preceding numbers. I realize where the problem stems from. It's because I have a return 0 at the end but I can't take that out because it will reach the end of a non-void function and in this manner, it returns 0 twice.

Can someone please help me fix this and give me an efficient method to address this problem?

EDIT: example: user inputs: 1 2 3 4 5 8 0

it should output:

0 8 5 4 3 2 1

my program will output: 0 0 8 5 4 3 2 1

4

4 回答 4

2
void revList()
{
 int num = 0;
 scanf("%d", &num);

 if (num != 0)
     revList();

 printf("%d\n", num);       
}

如果你想知道原因,我会稍微解释一下。

首先,该函数不需要返回整数,因为您正在从用户那里收集数字并将其全部打印在一个地方 - 根本不需要。

我猜您希望 0 成为一种“杀死命令”,因此,您不想打印它 - 因此我们将调用移至 printf 中的 if 语句。

编辑:

根据您的编辑,您明确表示您确实要打印收集的 0。代码相应地更改。

于 2013-10-02T18:23:00.157 回答
1
void revList()
{
   int num = 0;
   if( std::cin >> num ) {
      if( num ) 
         revList();
      std::cout << num << std::endl;
   }
}
于 2013-10-02T18:17:22.187 回答
0

你可以试试:

void revList()
{
    int num;
    scanf("%d", &num);

    if (num != 0)
    {
        revList();
    }
    printf("%d\n", num);
}
于 2013-10-02T18:22:26.653 回答
0

您可以这样做,避免使用虚拟参数,只需传入第一个数字,如果它不为零,则进行递归,直到达到零,然后在上一级返回时打印每个递归级别中的实际数字:

#include <stdio.h>
#include <stdlib.h>

int revList(int nValue)
{
    if(nValue != 0)
    {
        int nNextValue;
        scanf("%d", &nNextValue);
        revList(nNextValue);
        printf("%d", nValue);
    }
    return nValue;
}

int main(int argc, char** argv)
{
    int nValue;
    scanf("%d", &nValue);
    revList(nValue);
    return EXIT_SUCCESS;    
}
于 2013-10-02T18:33:18.017 回答