假设第一个整数是x。然后,我们定义一个[0] = X,序列的下一个元素被计算为:递归计算序列
a[n+1]=a[n]/2 if a[n] is even, and
a[n+1]=a[n]*3+1 if a[n] is odd.
The sequence continues till it reach value 1, then stop.
它看起来像这样75,226,113,340,170,85,256,128,64,32 ,16,8,4,2,1
这是我的代码(不使用递归)。 该prprmm它始终保持打印输出= 1。我已经检查过,但我不知道我错在哪里。 另一个问题是,其数据类型是最好的以声明变量x和数组a [](以最小化到最低容量?我们如何才能做到这一点与递归?
int main(void)
{
float a[100];
int i=0;
float x;
printf("Enter the value of x: ");
scanf("%f",&x);
a[0]=x;
printf("\n%f\n",a[0]);
do{
if (fmod(a[i],2)==0){
a[i+1]=a[i]/2;}
else{
a[i+1]=a[i]*3+1;
}
i++;
} while (a[i]!=1);
printf("The ouput value is:\n");
for (int j=0;j<i;j++){
printf("%2.2f\t",a[i]);
}
getch();
return 0;
}
这是一个**可怕的想法,使用浮点数来解决与整数有关的问题。 – 2013-05-27 05:42:34