我不得不仅使用递归设计一个标尺(没有循环)。用户输入标尺长度和刻度线的深度(高度)。我设法使用简单的for和while循环构建这个很好,但是当我尝试将其转换为递归时,我遇到了一些麻烦。我在运行文件结束时遇到堆栈溢出和第一次机会异常,但是,在错误消除之前,我得到了正确的输出。我一直在使用测试用例长度:4和深度:5,长度:12和深度:3。
如果有人知道我多少搞砸了我的递归努力,我全都听见了。
#include <iostream>
#include <string>
using namespace std;
void solve (int, int, int, string, int);
int main()
{
int depth, length;
cout << "Enter a ruler length: ";
cin >> length;
cout << endl << "Enter a marking depth: ";
cin >> depth;
int i = 0;
string ruler = "";
int size = length * pow(2, (depth-1));
solve(length, depth, i, ruler, size);
int x;
cin >> x;
return 0;
}
void solve (int length, int depth, int i, string ruler, int size)
{
if (depth > 0)
{
int inc = pow(2, depth-1);
if (i <= (size))
{
if (i % inc == 0) {
cout << "|";
}
if (i % inc != 0) {
cout << " ";
}
solve (length, depth, ++i, ruler, size);
}
cout << "\n";
}
solve (length, depth-1, 0, ruler, size);
}
答案 0 :(得分:2)
您需要solve
递归函数的返回点,例如:
void solve (int length, int depth, int i, string ruler, int size)
{
if (depth > 0)
{
int inc = pow(2, depth-1);
if (i <= (size))
{
if (i % inc == 0) {
cout << "|";
}
if (i % inc != 0) {
cout << " ";
}
solve (length, depth, ++i, ruler, size);
}
cout << "\n";
}
else
{
return; //<<<---- return out
}
solve (length, depth-1, 0, ruler, size);
}