【发布时间】: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