【发布时间】:2016-04-17 06:24:05
【问题描述】:
我不确定问题可能是什么。我添加了“cout
但现在我看到发生了一个无限循环。
我实际上是在尝试计算 num = 0 需要多少次循环。
起初我以为是 num = count 在循环中。
有什么建议吗?提前致谢。
#include <iostream>
using namespace std;
// hailstone function prototype
int hailstone(int &num);
int main()
{
int val;
cout << "Enter integer" << endl;
cin >> val;
hailstone(val);
cout << val << endl;
return 0;
}
// Pass values by reference to hailstone function header
int hailstone(int &num)
{
do
{
int count = 0;
// If num is even
// Divide by two
if(num % 2 == 0)
{
num = (num / 2);
count++;
cout << count;
}
// If num is odd
// Multiply by 3 and add 1
else if(num % 2 != 0)
{
num = (num * 3) + 1;
count++;
cout << count;
}
// Assign the number of steps to num
num = count;
} while(num > 0);
// Return the number of steps
return num;
}
【问题讨论】:
-
你到底想做什么? count 总是大于 0 并且在循环结束时将它分配给 num 以便循环永远继续
-
在为您的算法编写代码之前,您的算法是否有意义?一眼看去,即使没有声明
num = count;,我也看不出num将如何长期递减 - 你会有一个无限循环 1 -> 4 -> 2 -> 1 -> 4 -> 2 -> 1 -> ...回应@Pooya,你想做什么? -
只需删除“num = count;”并将“return num”替换为“return count”,你就很成功了——至少和你的偶/奇算法一样好——但也许你真的在寻找 num 去 1,而不是 0。跨度>
标签: c++ infinite-loop