所以在我的程序的主要部分有一个部分,我调用hailstone函数来回答print语句中的问题。 而不是打印序列一次,它打印两次,我不知道为什么或如何解决它。 有没有办法解决这个问题并从函数next(n)中删除print语句? 另外,我想知道我的评论是否合适? 我很难写出合适的合同,所以对这些合同的任何提示和批评都会很棒。但主要的是让冰雹序列打印一次,而不是两次。
// 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;
}
答案 0 :(得分:2)
不要把打印声明放在下一个。把它放在冰雹里。 它出现了两次,因为它是从冰雹上打印过一次而且是从长度上打印过一次。