【问题标题】:The sequence I am calculating (hailstone) is printing twice when it needs to print once我正在计算的序列(冰雹)在需要打印一次时打印两次
【发布时间】:2018-07-19 16:40:40
【问题描述】:

因此,在我的程序的主要部分,我调用 hailstone 函数来回答打印语句中的问题。 它不是打印一次序列,而是打印两次,我不知道为什么或如何修复它。 有没有办法解决这个问题并从函数 next(n) 中删除 print 语句? 另外,我想知道我的cmets看起来还好吗? 我很难写出体面的合同,所以任何关于这些的提示和批评都会很棒。但主要是让冰雹序列打印一次,而不是两次。

// 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;
}

【问题讨论】:

  • 这是 C++ 程序中的 C 代码。如果您正在使用 C,请使用 C 编译器。如果你在做 C++,请使用 C++,而不是伪装成 C++ 的 C。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-03
    • 2020-05-21
    • 2013-08-23
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多