【发布时间】:2017-01-18 18:41:27
【问题描述】:
我很想取一个随机自然数,然后打印出从最后一个数字到输入的 collatz 猜想。 Collatz猜想的步骤是: (a) 从任何正整数 N 开始。 (b) 如果 N 是奇数,则将其乘以 3 并加 1。(即 N ← 3N + 1) (c) 如果 N 是偶数,则除以 2。(即 N ← N/2) (d) 重复。 它总是以 4 ->2->1->4->2->1... 结尾 我的电脑告诉我 (projectname).exe 在输入整数后停止工作。
最重要的一点可能是我们应该为猜想分配空间,如果用完就加倍。
我的代码是:
int main()
{
unsigned long int input =0;
int max =16;
long int *collatz;
collatz = malloc(max*sizeof(long int));
long int *n = NULL;
long int *u = NULL;
int counter=0;
printf("Please enter a natural number:");
scanf("%lu", input);
printf("%lu\n",input);
if (input <1)
{
printf ("ERROR, not a natural number");
return 1;
}
n = collatz;
*n = input;
while (*n!=1)
{
if (counter == max)
{
max = max*2;
collatz = realloc (collatz,max*sizeof(long int));
}
if ((*n)%2 == 1)
{
*n=(3*(*n))+1;
}
else if ((*n)%2 == 0)
{
*n=(*n)/2;
}
*u=*n;
n=n+1;
*n=*u;
counter++;
int *i =0;
for (i=n;*i!=input;i--)
{
printf("%lu\t",*i);
}
}
return 0;
}
我想我弄错了 realloc,大多数其他的东西对我来说都不是什么大问题(这并不意味着没有错误,可能是)。
感谢您的帮助!
【问题讨论】:
-
永远不要这样做
x = realloc(x, ...); -
为什么?我们被鼓励使用它...@0andriy