c++ - 动态数值系列

标签 c++ algorithm c++11 for-loop simplify

我正在尝试创建一个程序来打印第一个 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 号码输出的来源。

关于c++ - 动态数值系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49779678/

相关文章:

c++ - 模板化动态数组上的内存泄漏

c++ - 在 OSX 上链接 OpenGL 框架

algorithm - 如何确定(子集的笛卡尔积并集)是否等于(完整集的笛卡尔积)

不同复杂度的算法

C++删除 map 中的指针

c++ - 使用 C++11 initializer_list 实现类 std::array 容器

c++ - QT 程序包含带有 if-test-then block 的 bash 脚本以及内部问题错误中转义的必要引号

c++ - UML 中的 Const 函数规范

javascript - 比较不同大小和维度的数组

multithreading - 为什么在成员函数上调用std::thread时需要 'this'?