在C ++中不使用任何循环就打印模式
在这个问题上,给我们一个数字n。我们的任务是打印图案,将其减少到0或负数然后再增加到数字。
让我们举个例子来了解这个问题,
Input: n = 12Output: 12 7 2 -3 2 7 12
为了解决这个问题,我们将使用递归并在每次更新后调用该函数。使用flag变量保持更新轨迹,该变量告诉函数将数字增加或减少5。
示例
以下代码提供了我们解决方案的实现,
#include <iostream>using namespace std;
void printNextValue(int m){
if (m > 0){
cout<<m<<'\t';
printNextValue(m - 5);
}
cout<<m<<'\t';
}
int main(){
int n = 13;
cout<<"The pattern is:\n";
printNextValue(n);
return 0;
}
输出结果
The pattern is −13 8 3 -2 3 8 13
以上是 在C ++中不使用任何循环就打印模式 的全部内容, 来源链接: utcz.com/z/338129.html