【问题标题】:How do I find the starting number from the sequence with the Max Value如何从具有最大值的序列中找到起始编号
【发布时间】: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


【解决方案1】:

我猜你现在自己解决了这个问题。但无论如何,让我们回答这个问题,这样它就不是 0 答案计数。

错误在该行:

// maxIndex will be the idex at maxValue or address
maxIndex = maxValues[i];

您存储的不是索引,而是值。这可能是一个很大的价值,因此超出了界限。

正确的解决方法是:

// maxIndex will be the idex at maxValue or address
maxIndex = i;

应该可以的。

只是为了好玩,我使用算法库创建了一个“更现代的 C++”元素解决方案。请看:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

// Collatz Sequence and its max value
struct CollatzSequence {

    CollatzSequence() {}

    // This will construct the collatez sequence and calculate the max value
    explicit CollatzSequence(unsigned int value); 

    // Values of the Collatz Sequence
    std::vector<unsigned int> data{};

    // The maximum value of all values of the Collatz sequence
    unsigned int maxValue{ 1U };
};

// Constructor for the Collatz Sequence. Will calculate all values of the sequence and the maxim value
CollatzSequence::CollatzSequence(unsigned int value) {

    // We calculate values as long as we did not find 1, always the last vale 
    // (There is no mathematicla evidence that this is always true)
    while (value > 1U) {

        // Store the current calculated value
        data.push_back(value);

        // Check, if this is the biggest value so far, and, if so, store it
        maxValue = std::max(value, maxValue);

        // Calculate next value in the row according to the Collatz Sequence rules
        value = ((value & 1U) == 0) ? (value >> 1U) : (3U * value + 1U);
    }
    // Always add 1 as the last element. This we do not need to calculate
    data.push_back(1U);
}

int main() {

    // Inform user to enter start end end value
    std::cout << "Calculate Collatz sequences. Please specify a range, a start and a end value:\n";

    // Read the start value and check, if this worked
    if (unsigned int rangeStart{}; std::cin >> rangeStart) {

        // Now read end value and check, if a correct range has been specified
        if (unsigned int rangeEnd{}; (std::cin >> rangeEnd) && rangeStart <= rangeEnd) {

            // Create a vector for Collatz Sequences. Allocate sufficent elements for the specified range
            std::vector<CollatzSequence> sequences(rangeEnd - rangeStart + 1);

            // Create all requested sequences
            std::generate(sequences.begin(), sequences.end(), [i = rangeStart]()mutable { return CollatzSequence(i++); });

            // Get the max element 
            std::vector<CollatzSequence>::iterator mve = max_element(sequences.begin(), sequences.end(),
                [](const CollatzSequence& cs1, const CollatzSequence& cs2) { return cs1.maxValue < cs2.maxValue; });

            // Show result to the world
            std::cout << "Max Value: " << mve->maxValue << " (" << mve->data[0] << ")\n";
        }
        else {
            std::cerr << "\n*** Error: Invalid range specified\n";
        }
    }
    else {
        std::cerr << "\n*** Error: Could not get start value for range\n ";
    }
    return 0;
}

【讨论】:

  • 当我更改 maxIndex = i; 时,我能够打印,但是这没有打印正确的序列起始编号,它打印了最后一个迭代的序列起始编号。
最近更新 更多