1

假设第一个整数是 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;
}
4

4 回答 4

4

问题是它一直保持打印输出= 1

当然,因为你总是输出数组中最后一个之后的数字(你的程序甚至有未定义的行为)。

另一个问题是,哪种数据类型最适合为变量 x 和数组 a[] 声明(以最小化容量?

两者都可以是一个unsigned long long,你甚至不需要一个数组。

char buf[0x100];
fgets(buf, sizeof(buf), stdin);
unsigned long long n = strtoull(buf, NULL, 10);
while (n > 1) {
    printf("%ull\n", n);
    n = n % 2 ? 3 * n + 1 : n / 2;
}
于 2013-05-27T05:49:37.313 回答
3

您只需使用递归方式在单个 while 循环中进行所有计算...替换这部分代码...

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]);
}

用类似的东西代替它....

    while(a[i] > 1){
     printf("\n%f\n",a[i]);
     if(fmod(a[i],2)==0){
       a[i+1]=a[i]/2;
     }else{
       a[i+1]=a[i]*3+1;        
     }
     i++;
    }

我没有测试它,但如果你不想使用任何外部函数进行计算,这个问题的递归的主要思想应该是这样的。这种递归方式也解决了总是打印 1 的问题。正如我所看到的,您已经得到了关于在代码中一直打印 1 的答案。您可以使用 long int 而不是浮点数组。我认为这是个好主意。然后您必须通过将数组 a[i] 和 a[i+1] 替换为 int 变量来更改代码。

对不起,我的英语不好。英语不是我的母语。谢谢。

于 2013-05-27T06:16:25.850 回答
1

它总是打印 1 的原因是您在 for 循环中使用了错误的变量

for (int j=0;j<i;j++){
    printf("%2.2f\t",a[i]);
}

a[j]您不应该访问a[i]. i在循环中是常数。你应该把它改成

for (int j=0;j<i;j++){
    printf("%2.2f\t",a[j]);
}
于 2013-05-27T05:46:12.953 回答
1

你的问题的一部分,

问题是它一直保持打印输出= 1

printf("The ouput value is:\n");
    for (int j=0;j<i;j++){
        printf("%2.2f\t",a[i]); //<--- use a[j] to print instead of a[i]
    }
于 2013-05-27T05:47:03.287 回答