我要解决的问题是要获取用户的数字输入,然后从该数字下倒数5个,直到我达到负数,然后返回5直到5我回到这个数字。我必须仅使用递归完全没有循环来做到这一点。代码接缝要在大部分时间工作,直到该值在0时倒退。
void Func(int num, int base, bool flipped)
{
cout << num << endl;
if (flipped == false && num > 1)
{
Func(num - 5, base, flipped);
}
flipped = true;
if (num < base)
{
Func(num + 5, base, true);
}
return;
}
我从上述代码中获得的输出,输入为17是:17,12,,7,,2,,-3,2,,7,,12,,17,7,,12,,17,12,,17,17。
由于某种原因,第二次递归中似乎存在问题。到目前为止,我尝试过的是使Bool静态并添加返回声明。谢谢您的帮助!
尝试以下:
#include <cstdlib>
#include <iostream>
int recount(int num)
{
std::cout<<num<<'n'; \Prints the current num
if(num >= 0) \checks that num is positive
{
\recursively call the function counting down by 5
std::cout<<recount(num-5)<<'n';
}
\count up by 5 as we go back up
return num + 5;
}
int main()
{
recount(17); \ gives desired output
return EXIT_SUCCESS;
}