[英]How to fix infinite loop in simple C++ function?
我是 C++ 的初学者,代码是作业的一部分。 我遇到程序无限循环的问题。 我知道无限循环按顺序(n)发生,但我不明白为什么它是无限循环。 我已经一步一步评估了这个过程,但我似乎遗漏了一些东西。
例如:我面临的一个问题:n = 7,序列打印:7 22 22 22 22 22
#include <cstdio>
using namespace std;
// next(n) returns the value that follows n in the hailstone sequence.
// Example: next(7) = 22, next(22) = 11, etc.
// Since the hailstone sequence ends at 1, n is required to be > 1.
int next (int n)
{
while (n > 1)
{
if (n%2 == 0)
{
return n/2;
}
else
{
return 3*n+1;
}
}
return 1;
}
// sequence(n) executes next(n) in a loop to print the next integer(s)
// in the hailstorm sequence, starting from n until ending with 1.
void sequence(int n)
{
int nextNum = n, x = next(nextNum);
while (nextNum > 1)
{
printf("%i", nextNum);
nextNum = x;
break;
}
if (nextNum == 1)
{
printf("%i", 1);
}
}
int main()
{
int n;
printf("Enter n: ");
scanf("%i", &n);
sequence(n);
return 0;
}
考虑以下:
while (nextNum > 1)
{
printf("%i", nextNum);
nextNum = x;
break;
}
在这里, x
永远不会改变。 因此, nextNum
也永远不会改变。 这使得循环要么无限期地执行,要么根本不执行。
您的意思是在循环体内部而不是外部调用next()
吗?
另请注意,鉴于循环体始终returns
, next()
中的while (n > 1)
是空操作。
首先,@NPE 建议在 while 循环中不改变nextNum 的值。 您可以直接为 nextNum 赋值,而无需使用变量 x。
第二件事是你为什么在循环中使用break语句。 你可以这样写:-
while (nextNum > 1)
{
printf("%i", nextNum);
nextNum = next(nextNum);
}
现在nextNum在每次循环迭代中都会有新值。 希望这会帮助你。 :-)
您实际上可以使用此代码来生成冰雹序列。
#include <cstdio>
using namespace std;
int main()
{
int n;
printf("Enter n: ");
scanf("%i", &n);
printf("%i\t",n);
while(n>1)
{
if(n%2==0)
{
n=n/2;
}
else
{
n=(3*n)+1;
}
printf("%i\t",n);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.