![](/img/trans.png)
[英]How do I use recursion to loop my code (when user enters invalid input, it prompts them again)?
[英]How can I use recursion to reverse the user input?
我知道這是一個非常瑣碎的問題。
我正在嘗試編寫一個程序,該程序將不斷要求用戶輸入為int值,直到用戶輸入0為止,此時它將終止並以相反的方式打印出所有數字。 這是我到目前為止的內容:
int revList(int num)
{
if (num != 0)
{
scanf("%d", &num);
printf("%d\n", revList(num));
return num;
}
return 0;
}
我的主要方法是:
int revList(int);
printf("%d", revList(1));
revList
的1是任意選擇的,即使編譯器在第一次迭代中沒有用,也可以滿足編譯器的要求。
我知道我的代碼可能效率不高,並且沒有正確使用遞歸。
該代碼可以工作,但是有1個問題:它打印兩次0,然后打印前面的數字。 我意識到問題出在哪里。 這是因為我在結尾處有一個返回0,但我無法取出它,因為它將到達非void函數的結尾,並且以這種方式,它會返回0兩次。
有人可以幫我解決這個問題,並為我提供解決此問題的有效方法嗎?
編輯:例如:用戶輸入:1 2 3 4 5 8 0
它應該輸出:
0 8 5 4 3 2 1
我的程序將輸出:0 0 8 5 4 3 2 1
void revList()
{
int num = 0;
scanf("%d", &num);
if (num != 0)
revList();
printf("%d\n", num);
}
如果您想知道原因,我會做一點解釋。
首先,該函數不需要返回整數,因為您是從用戶處收集數字並將其全部打印在一個位置中-根本不需要。
我猜想您希望0成為一種“ kill命令”,因此,您不想打印它-因此為什么我們將調用轉移到if語句內的printf。
編輯:
根據您進行的編輯,您可以清楚地表明確實要打印收集到的0。代碼已相應更改。
void revList()
{
int num = 0;
if( std::cin >> num ) {
if( num )
revList();
std::cout << num << std::endl;
}
}
您可以嘗試:
void revList()
{
int num;
scanf("%d", &num);
if (num != 0)
{
revList();
}
printf("%d\n", num);
}
您可以這樣做,避免使用啞元參數,只需傳入第一個數字,如果不為零,則進行遞歸直到達到零為止,然后在上一個遞歸返回時在每個遞歸級別中打印實際數字:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.