c++ - hailstone sequence c++ 计算序列长度所需的函数。无限循环问题

标签 c++ algorithm loops

我需要编写一个函数来计算并返回先前在已有函数中计算的冰雹序列的长度。 我尝试过的一切都给了我一个无限循环的“22”。 数组是不允许的。一切都必须用循环来完成,每个函数只能有一个循环。

我主要尝试使用前面的函数和 length++;添加到他们。 但我只是不知道该怎么做。

#include <cstdio>
using namespace std;

// The function next(n)takes an integer value n and 
// returns the number that follows n in a hailstone sequence. 
// For example: next(7) = 22 and next(22) = 11.

int next(int n)
{
  if (n > 1)
  {            
    if ((n % 2) == 0 )
    {
      n = n / 2;
    }
      else
      {
        n = 3 * n + 1;
      }
    printf("%i ",n); 

  }          
  return 0;
}

// The function hailstone reads int n and 
// prints its entire hailstone sequence.

void hailstone(int n)
{
  while(n>1)
  {
    next(n);
  }
} 

int length(int n)
{
  int length = 1;
  return length;
}

int main()
{
  int n; 

  printf("What number shall I start with?");
  scanf("%i", &n);

  printf("The hailstone sequence starting at %i is: ", n);
  hailstone(n);


  printf("The length of the sequence is: %i", length(n));

  return 0;
}

最佳答案

问题是您没有更改 n 值。试试这个:

int next(int n)
{
  if (n > 1)
  {            
    // As before
  }          
  return n;
}

注意 return n; 返回序列中的下一个值。接下来我们需要:

void hailstone(int n)
{
  while(n>1)
  {
    n = next(n);
  }
} 

我将其更改为 n = next(n);,因此我们在序列中选取新值。

此外,长度可以通过以下方式计算:

int hailstone(int n)
{
  int length = 0;
  while(n>1)
  {
    n = next(n);
    length++;
  }
  return length;
} 

这会计算我们调用 next() 的次数。

关于c++ - hailstone sequence c++ 计算序列长度所需的函数。无限循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48677133/

相关文章:

c++ - 绑定(bind)参数到 ansi c 回调

javascript - 如何使用 Javascript 使用嵌套循环打印到外循环的输出中?

python - 试图创建一个解决迷宫的程序,但它卡在了特定的路径上

python - 查找并替换列表宽度 Python 中的空行

python - 如何获得所有可能的排列?

c++ - 将二维数组元素复制到另一个具有另一个大小的二维数组

c++ - 为什么 std::vector 零初始化它的内存?

c++ - Code::Blocks、MinGW、libsdl 和 GNU C++ 编译器:对 `WinMain@16 的 undefined reference

python - 如何在 Python 中生成范围的多个深度列表?

algorithm - 给定一个短语,如何判断它是否是一个名字?