【发布时间】: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