使用递归的c++数字模式函数

Number Pattern Function in c++ using recursion

本文关键字:数字 模式 函数 c++ 递归      更新时间:2023-10-16

使用递归实现以下函数。不要使用任何局部变量或循环。

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),但在下一次调用时,您将调用模式,33603360 < 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;
}