c++ - 我正在计算的序列(冰雹)在需要打印一次时打印两次

标签 c++ loops if-statement while-loop collatz

所以在我的程序的主体中有一个部分,我在其中调用冰雹函数来回答打印语句中的问题。 它不是打印一次序列,而是打印两次,我不知道为什么或如何修复它。 有没有办法解决这个问题并从函数 next(n) 中删除打印语句? 另外,我想知道我的评论是否合适? 我很难写出像样的契约(Contract),所以任何关于这些的提示和评论都会很棒。但最主要的是让冰雹序列打印一次,而不是两次。

// Program hailstone takes a number and gives a sequence of 
// numbers starting with the input(n). The sequence alogrithm
// is (3n+1) then the next number is the previous divided by two.


#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 n;
}

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

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

// Parameters: int length, int n
// Uses next function, to calculate the length of the sequence.
int length(int n)
{
    int length = 1;
    while (n > 1)
    {
        n = next(n);
        ++length;
    }
    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("\nThe length of the sequence is: %i", length(n));

  return 0;
}

最佳答案

不要把 print 语句放在 next 中。把它放在冰雹中。 它出现了两次,因为它一次是从冰雹打印的,一次是从长度打印的。

关于c++ - 我正在计算的序列(冰雹)在需要打印一次时打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48696869/

相关文章:

java - 在数组中输入两次相同的数字

c# - "Inline temporary variable"(IDE0019) 修复在与接口(interface)一起使用时导致语法错误

c++ - 为什么我无法通过 lambda 捕获 "this"指针?

c++ - 我使用什么样的循环来读取文件?

javascript - 根据数据属性更改多个项目的颜色

C 代码和条件的正确语法

javascript - 如何检查 Handlebars 中的对象是否为空if语句?

c++ - 关于在不调用复制构造函数的情况下返回 STL 容器数据成员

c++ - gluBuild2DMipmaps 内存泄漏

c++ - C++ 中的 HashMap (int, string[])