【发布时间】:2026-01-08 11:25:06
【问题描述】:
在我的代码中,我计算了从开始到结束范围的 Collaz 序列。我运行了代码,除了具有最大值的序列的起始元素之外,所有内容都正确打印。我调试并看到我的最大值是正确的,但是我最终打印了具有最大值的序列的起始编号的结尾。我尝试重置 i 并且我还尝试查看我的 if 语句是否有问题
理想情况下,一旦正确,它应该看起来像这样 示例程序:
开始:1
结束:6
最大值:16 (3)
这是我的代码
int main()
{
// This declare the int start and end and prints them to the user as well as takes what the user gives
int start, end;
std::cout << "Start: ";
std::cin >> start;
std::cout << "End: ";
std::cin >> end;
// Here a vector called sequences is created. This holds a Collatz Sequences
std::vector<CollatzSequence> sequences;
int i = start;
while (i <= end)
{
sequences.push_back(CollatzSequence(i));
i = i + 1;
}
{
// A vector is made to hold the collatz sequences
std::vector<int> maxValues;
i = 0;
while (i < sequences.size())
{
maxValues.push_back(sequences[i].getMax());
i = i + 1;
}
// Here this declares varibles as intagers
int max = maxValues[0];
int maxIndex = 0;
{
// The i (index) is declare as integer
int i = 1;
// While i is less then the size of the vector maxValues
while (i < maxValues.size())
{
// If true (the element at maxValue is greater then the max)
if (maxValues[i] > max)
// max value will be that element
max = maxValues[i];
// maxIndex will be the idex at maxValue or address
maxIndex = maxValues[i];
// i is then incremented which mean it will go through the sequence at each address
i = i + 1;
}
std::cout << "Max Value: " << max << " (" << sequences[maxIndex].getStart() << ")\n";
}
}
这里是我定义函数的地方
CollatzSequence::CollatzSequence(int start)
int CollatzSequence::getMax()
{
int max = getNumbers()[0];
{
for (int i = 1; i < getNumbers()[i]; i++)
if (getNumbers()[i] > max)
max = getNumbers()[i];
}
return max;
}
int CollatzSequence::getStart()
{
int start = getNumbers()[0];
return start;
}
std::vector<int> const & CollatzSequence::getNumbers()
{
return numbers;
}
如果您看到错误但我没有看到或者我做错了什么,请告诉我。我试图只发布需要的内容而不发布 4 个文件。感谢您的宝贵时间。
【问题讨论】:
-
您发布了一个
main函数,所以从那里开始并发布获取main编译、链接和运行所需的内容。 -
// The i (index) is declare as integer您还应该使用更有意义的变量名称,而不是像i这样的一个字母名称。如果您看一下main,您会声明两个i变量,后者踩在第一个变量之上。也许这就是您遇到的问题。 -
"// 这里将变量声明为整数" 像这样的注释是没有用的。阅读您的代码的唯一人是程序员,因此编写任何程序员只需通过阅读代码即可轻松获得的信息的 cmets 是没有意义的。相反,写 cmets 来解释你的代码在更高层次上做了什么,例如“这个函数返回数组中最大值的索引”。
标签: c++ vector indexing collatz