我是C++的初學者,代碼是作業的一部分。我遇到了程序無限循環的問題。我知道無限循環發生在序列(n)中,但我不明白爲什麼它是無限循環。我已經逐步評估了這個過程,但我似乎錯過了一些東西。如何修復簡單C++函數中的無限循環?
例:有問題的我面臨: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;
}
該行應該等於nextNum = next(nextNum),當next()返回一個值時nextNum不會改變嗎? –
@MTee *但它不是*。僅僅因爲你在聲明中放置了'x = next(nextNum)'並且''x'的初始化*並不意味着處處出現'x',因此今後相當於替換表達式'next(nextNum)'。 'x'不是一些預處理宏。這是一個變量。 – WhozCraig
啊,這是一個很好的見解。你可能會認爲'while ='語句'x = next(nextNum)'的行可能意味着「每次我引用x我希望它是下一個(nextNum)」,但事實並非如此!你只是說你*用'next(nextNum)'的值初始化*'x'。從那時起,'x'將總是*是你首先初始化的那個值,除非你將它改變爲別的東西。重要的是,'='沒有**不**意味着平等,這意味着**賦值**。 – rwols