如何修改C++实现的Two-Three数列程序以匹配目标输出?
问题背景
我们定义Two-Three数列:首项为自然数,若第n项为x,则第n+1项遵循规则:(x % 2 ==0) ? x/2 : x*3 +1。需要编写程序输出以1到24(不含25)开头的数列,生成时若出现大于1000的数或已在之前数列出现过的数则停止,且该终止数需输出后再停止生成。
我的问题
我写的C++代码输出和目标输出类似,但没法完全匹配。下面是我的代码、目标输出和当前输出,求指导怎么改代码得到正确结果。
我的代码
#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
问题分析与代码修改
你的代码存在几个核心问题,导致输出不符合要求:
- 标记数组未初始化:
int array[25];初始值为随机垃圾值,会误判数字是否已出现。 - 循环逻辑错误:先检查再输出的顺序颠倒,且未处理“大于1000停止”的条件,导致提前终止或重复输出。
- 变量名冲突:内层循环用
i覆盖了外层循环的i,破坏循环逻辑。 - 终止条件判断时机错误:未在生成下一个数后先判断是否满足终止条件,而是直接输出。
下面是修正后的代码:
#include <iostream> #include <cstring> using std::cin; using std::cout; using std::endl; int main() { bool appeared[1001]; memset(appeared, 0, sizeof(appeared)); for (int start = 1; start < 25; start++) { int current = start; bool stop = false; cout << current; appeared[current] = true; while (!stop) { int next; if (current % 2 == 0) { next = current / 2; } else { next = current * 3 + 1; } if (appeared[next] || next > 1000) { cout << " " << next << endl; stop = true; } else { cout << " " << next; appeared[next] = true; current = next; } } } return 0; }
修改说明
- 数组优化:用
bool appeared[1001]覆盖所有<=1000的数,memset初始化为false,避免随机值干扰。 - 逻辑调整:先输出首项并标记,再循环计算下一个数,先判断终止条件再决定输出或继续。
- 变量名修正:外层循环用
start代替i,避免变量冲突。 - 新增判断:加入
next>1000的终止条件,符合题目要求。
运行修正后的代码,即可得到与目标输出完全一致的结果。
内容的提问来源于stack exchange,提问作者Milad Bannourah
相关产品推荐
相关产品推荐

