修改我的反向字符串函数以添加递归。不幸的是,我的程序一直在崩溃。
在 Visual Studio 中单步执行我的代码,出于某种原因,监 window 口会说 i 等于字符串的长度(即退出 while 循环的终止条件)。我最后一次跨过它,它说我现在比字符串长度少一。然后它永远停留在 while 循环中。
我知道这听起来很困惑,所以我举个例子。我输入“海绵宝宝”,它会执行我想要的所有操作(即说海绵宝宝的长度是 9,打印“bobegnopS”,将 i 递增到字符串长度等),但随后它说我现在是 8(即它是就在 9) 并且永远不会退出 while 循环。
这是我的 ReverseString() 函数:
void ReverseString(char * string, bool stringReversed, int stringLength, int i)
{
i++;
if(!stringReversed)
{
while(*string != '\0')
string++;
}
stringReversed = true;
while(i < stringLength)
{
string--;
std::cout << *string;
ReverseString(string, stringReversed, stringLength, i);
}
}
调用如下:
case 3:
//Learn By Doing 16.6
{
char string[BUFFER_LENGTH];
bool stringReversed = false;
int base = 0;
int exponent = 0;
std::cout << "\nEnter base: " << std::endl;
std::cin >> base;
std::cout << "\nEnter exponent: " << std::endl;
std::cin >> exponent;
//Print pow
NewLine();
std::cout << base << " to the " << exponent << " is " << pow(base, exponent);
//Reverse string using recursion
std::cout << "\nEnter string: " << std::endl;
std::cin >> string;
NewLine();
int stringLength = strlen(string);
int i = 0;
ReverseString(string, stringReversed, stringLength, i);
}
最佳答案
当你编写递归函数时,你总是需要指定停止条件。想象一下,您想编写朴素的阶乘递归实现。所以想法是这样计算:
n! = n * (n-1) *...*2*1
如果你查看序列,你会发现你需要在值 1 处停止。所以简单的递归实现可能是这样的:
int factorial( int n )
{
// stop when we reached 1
// otherwise we never finish
if( n == 1 ) return 1;
// now do the magic
return n * factorial( n - 1 );
}
您是否需要返回值的事实不会改变您需要设置停止条件的事实,否则您的递归函数将永远不会停止。
关于c++ - 使用递归后程序爆炸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15036873/