如果您先输入 1 然后输入 5,此代码的最终输出是...
The longest sequence with a start value in the range [1, 5] has 8 elements.
但我得到的是 {16 个元素}。
我认为问题可能出在我的计数器系统和返回上。有人对我如何解决这个问题有任何建议吗?
#include <iostream>
using namespace std;
// Functions
void getUserInput(int &start, int &end);
int longestSequence(int minimum, int maximum);
int getNextElement(int x);
string generateSequence(); // still need to write definition
int counter = 1;
int main()
{
int minimum;
int maximum;
int last;
getUserInput(minimum, maximum); //
last = longestSequence(minimum, maximum); // starts longest sequence counter
cout << "The longest sequence with a start value in the range [" << minimum
<< ", " << maximum << "] has " << last << " elements." << endl;
return 0;
}
void getUserInput(int &start, int &end)
{
cout << "Enter the min of the range for the sequence to start " << endl;
cin >> start;
cout << "Enter the max of the range for the sequence to start " << endl;
cin >> end;
}
int getNextElement(int x) // // This function does the 3n+1 computation
{
if (x != 1) // Checks for the end of the sequence. The end being when the number is 1.
{
counter++;
if (x % 2 == 0) // checks if its even
getNextElement(x / 2); // takes the new number through the function again
else
getNextElement(x * 3 + 1); // takes the new number into the function again
}
cout << "This is in getNextElement" << counter << endl;
return counter; // this is returned as length in the longestSequence function.
}
int longestSequence(int minimum, int maximum) // this function compares all the sequence lengths within the range of minimum and maximum.
{
int max = 0; // Longest seqence
for (int i = minimum; i <= maximum; i++)
{
int length = getNextElement(i); // length is a temp that will hold the longest seqence
if (length > max) // this loop validates if the newest "length" from the sequence is bigger than the previous one
cout << "This is in the longest sequence loop ... length" << length
<< endl;
cout << "This is in the longest sequence loop AS MAX" << length << endl;
max = length; // after the first run of the loop, max stores the longest seqence, and updates it after each run of the for loop if its longer
// counter = 1; not sure why this is here
}
cout << "This is in longest sequence.... max " << max << endl;
return max;
}
最佳答案
在调用 int length = getNextElement(i)
之前将计数器重置为 1。
您得到 16 作为输出,因为每次调用 getNextElement(i)
都会从上次函数调用离开的地方恢复 counter
。
counter=1;
int length = getNextElement(i);
就像你在自己的代码中错过的一样
// counter = 1; not sure why this is here
此外,max 不会更新为更大的长度,而是任何长度,因为它超出了用于检查更大长度的 if
的范围。因此,为 if
条件加上大括号,并将 max=length
移到其中。
关于c++ - 我的 C++ 程序没有跟踪我的 3n+1 最长序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441708/