我怎样才能摆脱创建 C++ 的空白行?

How do can I get rid of the blank lines that are created c++?


编辑: 感谢大家的快速和有益的答复。我现在开始工作了。这是因为我必须重置计数器。


我是来寻求帮助的,因为我的教授没有给我我需要的帮助。我是 c++ 的新手,我正在尝试编写一个程序来显示从 1 到 100 的所有整数,这些整数可以被 6 或 7 整除,但不能同时被两者整除。我必须每行显示 5 个数字。我得到它的工作,除了我在某些区域形成空白行。我不知道这是因为我如何设置柜台还是什么。

这是我得到的。


#include <iostream>

using namespace std;

int main()
{
    int counter = 0; // Counter for creating new lines after 5 numbers
    for (int numRange = 1; numRange <= 100; ++numRange) // Starts the loop of number 1 to 100
    {
        if (numRange % 6 == 0 || numRange % 7 == 0) // Makes the numbers divisible by 6 and 7
        {
            cout << numRange << " "; // Displays the output of the divisible numbers
            counter++; // Starts the counter

        }
        if (counter % 5 == 0) // using the counter to create new lines after 5 numbers displayed
        {
            cout << endl; // Creates a new line
        }
    }

    return 0;
}

这是输出的内容:






6 7 12 14 18


21 24 28 30 35
36 42 48 49 54

56 60 63 66 70

72 77 78 84 90
91 96 98

这就是它应该的样子

  6   7 12 14 18 
21 24 28 30 35 
36 48 49 54 56 
60 63 66 70 72 
77 78 90 91 96 
98

您看到的问题是因为您在 每个 循环上检查“5 个输出”,而不是仅在一个数字已经出现的循环上检查输出!因此,要解决 this 问题(还有其他问题),请将 counter % 5 == 0 测试放在前面的 if 块中:

    for (int numRange = 1; numRange <= 100; ++numRange) // Starts the loop of number 1 to 100
    {
        if (numRange % 6 == 0 || numRange % 7 == 0) // Makes the numbers divisible by 6 and 7
        {
            cout << numRange << " "; // Displays the output of the divisible numbers
            counter++; // Increments the counter
            if (counter % 5 == 0) // Only need this if we have done some output!
            {
                cout << endl; // Creates a new line
            }
        }
    }

另一个问题是,在这个需求中:

that are divisible by 6 or 7, but not both

您的代码不检查 "but not both" 部分(但这不是 'title' 问题,我不会做 all 你的作业一下子就完成了)。