【发布时间】:2021-09-19 04:56:14
【问题描述】:
到目前为止,对我来说,在递归函数中保留特定变量值的唯一方法是将其作为参数传递。但是这次我特别需要编写一个函数,它只接受两个整数作为参数,并在第一次迭代时接受一个字符串输入。
伪代码:
函数(int a,int b)
if a == 1 and b == 2 take a string as input else // do something with that string and print it
我想出的代码:
void f(int a, int b)
{
string s;
if (a == 1 and b == 2)
{
cin >> s;
}
//do something with a, b and string
//some recursive calls based on conditions
/* for example */
if (!(a == 3 and b == 6))
{
f(a + 1, b + 2);
}
cout << s << "\n";
}
//and then call this function in the main function as f(1, 2);
我知道我的代码有什么问题,但我不明白如何解决它。有没有办法在递归函数中获取输入并在另一个递归调用中打印它的值?
【问题讨论】:
-
作弊:如果您需要在第一个也是唯一的第一个递归上做一些事情,插入另一个函数来处理第一个情况。在您的情况下,
f要求输入字符串,完成工作的第一步,然后调用f_inner调用自身。如果您可以使用f和f_inner调用的另一个小函数来消除代码重复,那就去做吧。 -
我不明白这个问题。在我看来,示例代码回答了这个问题。
-
你知道
static是什么意思吗? -
@user4581301 我想我明白你想说什么,我会试一试。
-
小心“用 a、b 做一些事情,并根据条件将一些递归调用串起来”,永远记得放一个终止条件。另外,如果解决了,请考虑stackoverflow.com/help/self-answer