我之前在java中使用数组完成了它,但是我在尝试将其转换为使用当前代码时遇到了麻烦。我还是C ++的新手,也在寻找一些批评。我的代码看起来像一团糟,想要了解如何使它看起来更整洁。我试图养成先编写合同然后编写代码的习惯。 (老实说,这帮助我理解我做得更好)。我的意思是,它不干净。我想在之后清理它,但我想尝试修复这部分。我想要一些建议。我将继续努力。
// This program takes a user defined number 'n'
// and runs it through a function that returns
// the number that follows 'n' in hailstone sequence.
// Since there is no number that follows 1 in the sequence,
// this function requires its parameter 'n' to be greater
// than 1.
/* example output
What number shall I start with? 7
The hailstone sequence starting at 7 is:
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
The length of the sequence is 17.
The largest number in the sequence is 52.
The longest hailstone sequence starting with a number up to 7 has length 17
The longest hailstone sequence starting with a number up to 7 begins with 7
*/
#include <algorithm>
#include <cstdio>
using namespace std;
int main(int argc, char** argv)
{
int n;
// hailLength will keep track of how many
// numbers are produced in the sequence.
int hailLength = 1;
printf("What number shall I start with? ");
scanf("%d", &n);
printf("The hailtone sequence starting at %d is: \n", n);
printf("%i", n);
printf(" ");
// While 'n' is not equal to 1 the function will calculate whether 'n' is even
// then it will divide n/2, otherwise it will compute 3n + 1 if n is odd.
while(n != 1)
{
if(n % 2 == 0)
{
n /= 2;
printf("%i", n);
printf(" ");
}
else
{
n = (3 * n) + 1;
printf("%i", n);
printf(" ");
}
hailLength++;
}
printf("\n");
printf("The length of the sequence is %i.", hailLength);
printf("\n");
// This line will display the largest value in the hailstone sequence.
// This portion is also broken.
int maximum(int n);
{
int k = 0;
int ans = n;
while(k != n)
{
k++;
if(ans < k)
{
ans = k;
}
}
//return ans;
printf("%u", ans);
//printf("%u", k);
printf("\n");
}
//printf("The largest number in the sequence is %i", max(n));
return 0;
}
答案 0 :(得分:1)
没有理由:
首先生成您的列表。
将该列表保存在某个地方,就像你明显的意图一样。
在生成整个列表并打印之后,返回然后找出其中最大的数字。
这样做当然是可能的,而且它不是火箭科学,但它仍然不必要地复杂化。简单地跟踪看到的最大数字就简单得多了......
int max;
...同时您正在生成列表。
那就是它。让我们开始吧:
scanf("%d", &n);
printf("The hailtone sequence starting at %d is: \n", n);
max=n;
您可以通过将max
设置为第一个数字来开始滚动。很明显,到目前为止,这是迄今为止最多的数字。
然后,在现有的for循环中,在计算下一个数字并显示之后,将其与max
的当前值进行核对:
}
if (n > max)
max=n;
hailLength++;
然后,当您的循环终止时,您将在max
中找到序列中最大的数字。
答案 1 :(得分:0)
你可以做这样的事情来找到最大值。
#include <algorithm> // std::max
int maxNumSoFar = n;
while( n != 1 ) {
maxNumSoFar = std::max(n, maxNumSoFar);
if( n%2 == 0) n /= 2;
else n = 3*n+1
}
printf("Max number seen is %d", maxNumSoFar);
此外,由于您使用的是C ++而不是C,因此您可能需要查看I / O的“cin”和“cout”,而不是使用C的“printf”和“scanf”。