使用递归的c++数字模式函数
Number Pattern Function in c++ using recursion
使用递归实现以下函数。不要使用任何局部变量或循环。
void pattern(unsigned int n)
//前提条件:n> 0;
//后置条件:输出由整数行组成。第一行
//是数字n,下一行是数字2n。下一行是
//数字4n,以此类推,直到你得到一个比
大的数字//4242。然后向后重复这个数字列表,直到返回
//to n.
/* n = 840时的输出示例:
840年1680年3360年6720年6720年3360年1680年840 */
//这是我的代码
#include <iostream>
using namespace std;
void pattern(unsigned int n)
{
if(n > 0)
{
cout << n << endl;
return pattern(n * 2);
}else if( n > 4242)
{
return pattern(n / 2);
}
}
int main()
{
pattern(840);
return 0;
}
//我的代码只是把n加倍,它不会除以原来的n
另外两个答案指出了其中一个问题(当n > 4242
为真时,n > 0
为真),但另一个问题是,如果n > 4242
,您只使用n / 2
调用pattern
。所以你会以"乒乓"来来回回结束。例如,在您在问题中显示的示例输出中,当您命中6720
时,您将其减半以调用pattern(3360)
,但在下一次调用时,您将调用模式,3360
自3360 < 4242
以来翻了一番。
我认为最明显的方法是把它分成两个函数,并添加一个"方向"布尔值,指示你是向上还是向下:
void pattern(unsigned int n) {
pattern_with_dir(n, true);
}
void patten_with_dir(unsigned int n, bool increase) {
if (n <= 0) {
return;
}
cout << n << endl;
if (n > 4242) {
pattern_with_dir(n, false);
} else {
if (increase) {
pattern_with_dir(n * 2, true);
} else {
pattern_with_dir(n / 2, false);
}
}
}
注意你也可以把它分成3个函数:
void pattern(unsigned int n) {
pattern_up(n);
}
void pattern_up(unsigned int n) {
cout << n << endl;
if (n > 4242) {
pattern_down(n);
} else {
pattern_up(n * 2);
}
}
void pattern_down(unsigned int n) {
if (n <= 0) {
return;
}
cout << n << endl;
pattern_down(n / 2);
}
但是最简洁的解决方案是使用递归堆栈来帮助你倒数:
void pattern(unsigned int n) {
// Going up
count << n << endl;
if (n <= 4242) {
pattern(n*2);
}
// this will be called "on the way back down"
count << n << endl;
}
void pattern(unsigned int n)
{
if (n > 0)
{
cout << n << endl;
if (n < 4242)
pattern(n * 2);
cout << n << endl;
}
}
if( n > 4242)
只在(n > 0)
不为真时计算。但是只要n > 4242
为真,n > 0
也为真。
它永远不会碰到else if,因为第一个条件(>0)仍然为真,并且它将在第一个if语句中结束。
生成第一个条件
if(n > 0 && n <= 4242) {
...
} else if(n > 4242){
...
}
或者if和else的反转if
if(n > 4242) {
return pattern(n/2);
} else if (n >0) {
return pattern(n*2);
}
// ConsoleApplication3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void pattern(unsigned int n)
{
cout << n << endl;
if (n > 4242) {
cout << n << endl;
return ;
}
pattern(n * 2);
cout << n << endl;
return ;
}
int _tmain(int argc, _TCHAR* argv[])
{
pattern(840);
return 0;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 在C++的一系列数字中查找重复模式
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 在此任务上遇到麻烦,我们需要使用指针和数组来找到文本文件中某些数字的平均值,中值和模式
- 编写模式识别'函数以查找特定顺序出现的数字?C++
- 从列表到数组C 查找模式或最常见的数字
- 在x86_64模式下,64 位数字不适合寄存器整数
- 通过2D阵列C 移动锯齿ZAG模式的数字
- 为什么 std::setprecision(6) 在固定宽度模式式传输超过 6 位数字
- c++rand()和来自boost的RNG生成相同的数字(在发布模式中),即使srand(0)也是如此
- 打印重复数字模式
- 如何在C++中生成具有奇怪模式的数字
- 无模式例外是什么意思?(数组中出现次数最多的数字)
- 查找 n 个数字的模式
- 嵌套循环:数字模式
- 以二进制模式扫描文件,并将十六进制字符解释为C++中的实际数字
- 使用递归的c++数字模式函数
- 创建一个数字模式
- 是否可以在CEdit控件的纯数字和字母数字输入模式之间切换
- 如何在C++中显示此数字模式