如何在c++中构建一个二三系列程序



我有这个CS问题说:

我们定义一个数列,它的第一项是某个自然数。如果序列中成员编号n的值为x,则该序列中(n +1)个成员的值为:(x % 2 ==0) ?X *3 +1.

您必须编写一个程序,打印从数字1到25(不包括)开始的两个或三个序列,但是当产生大于1000的值或已经出现在前一个序列中的值时,每个序列的创建将停止(因此从该数组开始产生的子序列已经产生)。生成的值必须重新显示,从而停止该系列的生产。

现在我写的代码输出与解决方案输出类似的结果,但它需要一些更改,以获得相同的确切结果,我无法弄清楚,这是我的代码。

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int array[25];
for (int i = 1; i < 25; i++)
{
int currentNum = i;
int theNumAfter;
bool occured = false;

while (occured == false)
{
for (int i = 0; i <= 25; i++)
{
if (array[i] == currentNum)
{
occured = true;
cout << endl;
}
}

array[currentNum] = currentNum;

cout << currentNum << " ";

if (currentNum % 2 == 0)
{
theNumAfter = currentNum / 2;
}
else
{
theNumAfter = (3 * currentNum) + 1;
}

array[theNumAfter] = theNumAfter;

cout << theNumAfter << " ";
currentNum = theNumAfter;
}
}
}

代码不接受任何输入,只有一个正确的输出,应该是这样的:

1 4 2 1
2
3 10 5 16 8 4
4
5
6 3
7 22 11 34 17 52 26 13 40 20 10
8
9 28 14 7
10
11
12 6
13
14
15 46 23 70 35 106 53 160 80 40
16
17
18 9
19 58 29 88 44 22
20
21 64 32 16
22
23
24 12

我代码的结果:

1 4
4 2
2 1 3 10
10 5
4 2
5 16 6 3
3 10 7 22
22 11 8 4
4 2 9 28 28 14
14 7
10 5
11 34 12 6
6 3 13 40 40 20
20 10
14 7 15 46 46 23
23 70
16 8 17 52 52 26 26 13
13 40 18 9
9 28 19 58 58 29 29 88 88 44 44 22
22 11

我应该在代码中修改什么,以便我们有匹配的输出。提前感谢

值大于1000时,每个系列的创建将停止或者生成一个在前一个序列中已经出现的值。

直到24,生成的值都不大于1000,但是发布的代码仍然有访问越界的错误:

int main()
{
int array[25];
//        ^^
for (int i = 1; i < 25; i++)
{
int currentNum = i;
int theNumAfter;

// ...
array[currentNum] = currentNum;
// ...
array[theNumAfter] = theNumAfter;
// ...
}
// ...
}

注意预期输出中有许多数字大于25。

我不确定这部分应该实现什么:

for (int i = 0; i <= 25; i++)
{ //            ^^^^^^^   it "checks" only the first 25 values that may occur
if (array[i] == currentNum)
{
occured = true;
cout << endl;      // <-- The duplicate should be printed before the newline.
// Here it should break out of the loop.
}
}
array[currentNum] = currentNum;
cout << currentNum << " ";

但是它不能产生预期的输出。

我将使用一个包含1000个bool的简单数组来记忆已经出现的数字。

#include <iostream>
int main()
{
constexpr int limit{ 1'000 };
bool already_seen[limit + 1]{};
for (int i = 1; i < 25; i++)
{
int current{ i };
while ( current <= limit  and  not already_seen[current] )
{
std::cout << current << ' ';
already_seen[current] = true;
if ( current % 2 == 0)
{
current /= 2;
}
else
{
current = (3 * current) + 1;
}
}
std::cout << current << 'n';
}
}

可测试的。

相关内容

最新更新