简体   繁体   English

为什么我的 Collatz 序列的 C 程序不打印最终值 (1)?

[英]Why doesn't my C program for the Collatz sequence print the final value (1)?

I am currently making a program for the collatz sequence on C, however the last value, which is 1, is not being printed.我目前正在为 C 上的 collatz 序列制作程序,但是最后一个值 1 没有被打印。 For example, when I input 8, the outcome must be 8 4 2 1, but it only prints 8 4 2, or when I input 5, it only prints 5 16 8 4 2. What can I put inside the while ( ) to print the complete answer?比如我输入8时,结果一定是8 4 2 1,但它只打印8 4 2,或者我输入5时,它只打印5 16 8 4 2。我可以在while ( )里面放什么来打印完整的答案? Thank you!!谢谢!!

void 
CollatzSequence(int n)
{

    int x = 1;

    do {
    x++;
        printf("%3d", n);
        if (n%2==0)
            n /= 2;
        else 
            n = 3 * n + 1;
    }
    while (  );

    printf("\n"); 
}

int 
main()
{
    int n;

    do {
        printf("Input an integer greater than 0: ");
        scanf("%d", &n);

        if (n <= 0)
            printf("Invalid input. Try again.\n");
    } while (n <= 0);

    CollatzSequence(n);

    return 0;
}

Code needs new loop exit condition.代码需要新的循环退出条件。

Loop is done once 1 is printed.打印1后循环完成。

Sample below.示例如下。

void CollatzSequence(int n) {
  for (;;) {
    printf("%3d", n);
    if (n == 1)
      break;
    if (n % 2 == 0)
      n /= 2;
    else
      n = 3 * n + 1;
  }
  printf("\n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM