【问题标题】:How do can I get rid of the blank lines that are created c++?如何摆脱创建 C++ 的空行?
【发布时间】:2020-02-29 19:28:12
【问题描述】:

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


我是来寻求帮助的,因为我的教授没有给我我需要的帮助。我是 C++ 新手,我正在尝试编写一个程序来显示从 1 到 100 的所有整数,这些整数可以被 6 或 7 整除,但不能同时被 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

【问题讨论】:

  • 实际输出与期望输出的详细信息可能会有用。
  • 现在会发生什么,您预计会发生什么?
  • 为什么不使用if (counter == 5) 进行测试? (您需要在正文中重置counter = 0;。)
  • for (int numRange = 1; ... 看起来不对。你不想for (int numRange = 0; 吗?
  • 当您的计数器没有更新时,它将打印新行。例如,对于 numRange=19 和 20,计数器仍然是 5,它会打印新行

标签: c++ for-loop if-statement counter


【解决方案1】:

您看到的问题是由于您在 每个 循环上检查“5 个输出”,而不仅仅是在输出数字的循环上检查!因此,要解决 这个 问题(还有其他问题),请将 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
            }
        }
    }

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

能被 6 或 7 整除,但不能同时被 6 或 7 整除

您的代码不会检查“但不是两者”部分(但这不是“标题”问题,我不会这样做全部一口气完成你的作业)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 2011-03-02
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2011-08-21
    • 2010-11-08
    • 1970-01-01
    相关资源
    最近更新 更多