C++ 回文递归不停止
我已经构建了这个框架,但是我遇到了一个无法捕捉的逻辑错误。为了总结它所做的事情,它将一个字符串传递给book函数,并检查第一个和最后一个字符,如果有相同的字符,则继续这样做,直到有一个字符剩余。如果字母不相同,则返回false。然而,当一个有效的回文被输入时,结果会被窃听——它会进入基本情况,但不会停止递归,当它实际上是一个回文时,结果会返回0。任何关于它为什么不停止的洞察都会很棒C++ 回文递归不停止,c++,recursion,palindrome,C++,Recursion,Palindrome,我已经构建了这个框架,但是我遇到了一个无法捕捉的逻辑错误。为了总结它所做的事情,它将一个字符串传递给book函数,并检查第一个和最后一个字符,如果有相同的字符,则继续这样做,直到有一个字符剩余。如果字母不相同,则返回false。然而,当一个有效的回文被输入时,结果会被窃听——它会进入基本情况,但不会停止递归,当它实际上是一个回文时,结果会返回0。任何关于它为什么不停止的洞察都会很棒 #include <iostream> #include <string> #includ
#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
#include <cstdio>
using namespace std;
bool book(string origWord, int len);
int main()
{
string a = "ABCDCBA";
cout << "Test:" << book(a, a.length() - 1);
return 0;
}
bool book(string origWord, int len)
{
bool status = false;
if (len <= 1)
{
status = true;
}
else if (tolower(origWord[0]) == tolower(origWord[len]))
{
book(origWord.substr(1, len - 1), len - 2);
}
return status;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
布尔书(字符串原语,整数);
int main()
{
字符串a=“ABCDCBA”;
库特
在这里,您丢弃了从book返回的值。您可能希望这样:
status = book(origWord.substr(1, len - 1), len - 2);
以下是控制如何通过此函数流动:
bool book(string origWord, int len)
{
bool status = false; // 1. status is FALSE
if (len <= 1) // 2. This branch is not taken
{
status = true;
}
else if (tolower(origWord[0]) == tolower(origWord[len])) // 3. This branch IS taken
{
book(origWord.substr(1, len - 1), len - 2); // 4. Say, this returns TRUE
// 5. but the return value is not used
}
// 6. control passes here after executing the function
// 7. local status is STILL FALSE
return status; // 8. return status, which is FALSE
}
bool book(字符串原形,整数长度)
{
bool status=false;//1.状态为false
如果(len)
bool book(string origWord, int len)
{
bool status = false; // 1. status is FALSE
if (len <= 1) // 2. This branch is not taken
{
status = true;
}
else if (tolower(origWord[0]) == tolower(origWord[len])) // 3. This branch IS taken
{
book(origWord.substr(1, len - 1), len - 2); // 4. Say, this returns TRUE
// 5. but the return value is not used
}
// 6. control passes here after executing the function
// 7. local status is STILL FALSE
return status; // 8. return status, which is FALSE
}
bool book(string origWord, int len)
{
if (len <= 1)
{
return true;
}
else if (tolower(origWord[0]) == tolower(origWord[len]))
{
// Use the RETURNED VALUE!
return book(origWord.substr(1, len - 1), len - 2);
}
return false;
}