递归功能,以打印每个新位置以进行控制



这是一个C 的家庭作业问题,因此我非常感谢在正确的方向上进行一些指导。问题要求输入一个正整数以表示位置。如果初始位置均匀,则新位置为d/2,如果奇数为3*d 1,则一直持续到位置为1。

ex:输入正整数:11

11:11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

的OJP

这是我通过迭代来工作的一些代码:

#include "stdafx.h"
#include <iostream>
using namespace std;
int ollyjumppattern(int d)
{
    if (d == 1)
    {
        return 1;
    }
    else if (d % 2 == 0)
    {
        return (d / 2);
    }
    else
    {
        return (3 * d + 1);
    }
}

int main()
{
    int target;
    cout << "Enter a positive integer: ";
    cin >> target;
    cout << "The OJP for " << target << ": ";
    if (target == 1)
    {
        cout << "1";
    }
    else
    {
        cout << target;
        while (target != 1)
        {
            cout << " " << ollyjumppattern(target) << " ";
            target = ollyjumppattern(target);
        }
        cout << endl;
    }
    return 0;
}

这就是我到目前为止的递归:

#include "stdafx.h"
#include <iostream>
using namespace std;
int ollyjumppattern(int d)
{
    if (d == 1)
    {
        cout << "1";
        return 1;
    }
    else if (d % 2 == 0)
    {
        int result = ollyjumppattern(d/2);
        cout << result << " ";
        return result;
    }
    else
    {
        int result = ollyjumppattern(3*d+1);
        cout << result << " ";
        return result;
    }
}

int main()
{
    int target;
    cout << "Enter a positive integer: ";
    cin >> target;
    cout << "The OJP for " << target << ": ";
    if (target == 1)
    {
        cout << "1";
    }
    else
    {
        cout << ollyjumppattern(target);
        cout << endl;
    }
    return 0;
}

当我尝试运行它时,此代码崩溃了我非常感谢任何提示

您的递归很好,代码中唯一的问题是打印错误的东西。您应该打印d,而不是result,因为完成了所有递归后,所有结果将仅为1

您也不需要在main()中测试target == 1,因为这将由功能本身处理。

#include <iostream>
using namespace std;
void ollyjumppattern(int d)
{
    cout << d << ' ';
    if (d == 1)
    {
        return;
    }
    else if (d % 2 == 0)
    {
        ollyjumppattern(d/2);
    }
    else
    {
        ollyjumppattern(3*d+1);
    }
}

int main()
{
    int target;
    cout << "Enter a positive integer: ";
    cin >> target;
    cout << "The OJP for " << target << ": ";
    ollyjumppattern(target);
    cout << 'n';
    return 0;
}

最新更新