【发布时间】:2013-05-27 05:38:50
【问题描述】:
假设第一个整数是 x。然后我们定义a[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
这是我的代码(不使用递归)。 问题是它一直打印 output=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;
}
【问题讨论】:
-
使用浮点数解决整数相关问题是一个可怕的想法。