动态数值系列

Dynamic numerical series

我正在尝试创建一个程序来打印第一个 200 个元素,该元素遵循特定的数字序列条件

1-1-3-6-8-8-10-20

但是没有显示,只有 200 个元素显示 802。我假设是因为 for 循环中的代码。我花了好几个小时思考如何将代码减少到工作中,我想不出别的。我很沮丧,需要你的帮助。

练习在代码注释上

//Print the following numerical series 1-1-3-6-8-8-10-20  until 200

#include <stdafx.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    int Num1=200, z = 0, x = 1, y = 1;

    cout << "\n\n1,";
    cout << " 1,";

    for (int i = 1; i <= Num1; i++)
    {
        z = y + 2;
        cout << " " << z << ","; //It will print 3
        z = z * 2;
        cout << " " << z << ",";//It will print 6
        z = z + 2;
        cout << " " << z << ",";//It will print 8
        z = z;
        cout << " " << z << ",";//It will print 8
        y = z;
    }
    cout << "\n\n";
    system("pause");
    return 0;
}

你循环了 200 次,每次循环,你都会打印出 4 个不同的数字。你也在开始时打印两次,所以 2 + 4 * 200 = 802,这是你的 802 号码输出的来源。

I assume is because of the code inside the "for" loop but I've hours thinking on how to reduce that code to the job and I cannot think anything else. I'm getting frustrated and need your help.

所以你基本上想简化你的代码。这可以通过注意重复来完成。 在那里你只能找到系列中的两种变化; +2x2 与前一个元素。

在每次迭代中,这可以通过以下方式实现:

  1. 如果提醒i%4 == 1i%4 == 3,需要增加2(假设1 <= i <= MAX
  2. 如果提醒i%4 == 0,只不过是2的乘法。

当你这样做时,你可以简单地忽略打印前两个和系列总数中的其他并发症。

也不是这样,您正在尝试获得该系列的 200 项,每一步都非常快地增加并超过 int 的最大限制。所以需要用long long代替

更新后的代码将如下所示:

#include <iostream>
typedef long long int int64;
int main()
{
    int size = 200;
    int64 z = -1;

    for (int i = 1; i <= size; i++)
    {
        if ((i % 4 == 1) || (i % 4 == 3))   z += 2;
        else if (i % 4 == 0)                z *= 2;
        std::cout << z << "\n";
    }

    return 0;
}

在此处查看输出:https://www.ideone.com/JiWB8W