我需要编写一个函数来计算并返回先前在已有函数中计算的冰雹序列的长度。 我尝试过的一切都给了我一个无限循环的“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/