[英]Reversing a number in C++ using Recursion
當我編寫這段代碼時,它會完成這項工作,但也會打印一些隨機的東西。
如果我的輸入是 32,它會在一行隨機數之后打印 23。 例子:
23 983748572819937482
我想知道這些隨機數是什么以及為什么要打印它們
#include <iostream>
using namespace std;
int reverse(int n) {
if (n==0){
cout << " ";
return 0;
}
else {
int lastdigit = n%10;
int firstdigit = n/10;
cout << lastdigit << reverse (firstdigit);
}
}
int main(){
int n;
cin >> n;
reverse (n);
}
由於您沒有捕獲返回值,因此此 function 應該是無效的,並且可以像這樣使用:
void reverse(int n) {
if (n==0){
cout << n
return;
}
else {
int lastdigit = n%10;
int firstdigit = n/10;
cout << lastdigit;
if(firstdigit != 0)
reverse (firstdigit);
}
}
此外,“firstdigit”的符號意味着它只是第一個數字,盡管它實際上是數字的 rest。 即: 545/10 = 54
您應該始終在啟用警告的情況下進行編譯,並且作為初學者始終將警告視為錯誤。
如果這樣做,您會看到reverse
不會在所有路徑上返回值。 因此,當您執行cout << reverse (firstdigit);
您嘗試打印reverse
返回的內容,即未定義的行為。
如果您像這樣實現 function (通過在其中打印),您的 function 不需要返回值。 所以這將起作用:
void reverse(int n) {
if (n==0){
cout << " ";
}
else {
int lastdigit = n%10;
int firstdigit = n/10;
cout << lastdigit;
reverse (firstdigit);
}
}
但是,我認為這不是練習的目的。 我認為您的 function 應該返回反轉的數字,而不是打印它。 所以想想你將如何修改 function 來實現這一點。
只需將您的停止條件更改為n <= 9
。 如果您繼續將一個數字除以 10,則 rest 不一定為零。
#include <iostream>
void reverse(int n) {
if (n <= 9) {
std::cout << n;
} else {
int lastdigit = n % 10;
int firstdigit = n / 10;
reverse(firstdigit);
std::cout << lastdigit;
}
}
int main() {
int n;
std::cin >> n;
reverse(n);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.