Collat​​z 序列使最后一个数字 1 重复

标签 c if-statement while-loop collatz

    // Define the recursive function.
    int collatz(int p1)
    {
        // While Loop Starting
        while (p1>1)
        {
      //when the number is even
        if(p1%2==0)
        {
            p1 = p1/2;
            printf("%d ", p1);
        //using recursion
            return collatz(p1);
        }
        // Case where number is odd.
        elseif
        {
            p1 = 3*p1+1;
           //print function
            printf("%d ", p1);
           //using recursion
            return collatz(p1);
        }
        }
     }  
    // Main body.
    int main()
    {
       // Declare the variable and initialized it.
      int p1= 4;
      //print function
     printf("User Entered value  : %d\n", p1);
       // Display the number 
        printf("%d\n", collatz(p1));
        //End
        return 0;
    }

输出:我得到的输出为: 2 ,1, 1 我不应该重复最后一个数字 1。您能纠正我犯错的地方吗?请做必要的事情。

最佳答案

编译 C 或 C++ 程序时应始终启用警告。如果您这样做了,编译器会警告您,您的函数 collat​​z 可能会终止而不返回值。 (如果参数为 1 会发生什么?)

这是未定义的行为,在 main 函数中使用可能不存在的返回值也是如此。

所以它碰巧在 main 中打印 1 只是一个偶然的机会。但无论它打印什么都会是错误的,因为您似乎期望输出仅限于 collat​​z 中打印的内容。

您可以尝试玩计算机并用铅笔和纸执行您的函数。不会花很长时间。当然,您也可以使用调试器。

关于Collat​​z 序列使最后一个数字 1 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37504681/

相关文章:

c++ - FFmpeg -- 使用硬件加速进行视频解码

PHP: while (time() < time()+2;){ echo "why does this not work ?"};

python - 验证值仍然导致类型错误?

c - ASM 约束副作用

c - struct epoll_event memset 还是没有 memset?

c - Socket编程端口号

jquery - 如何为 jQuery 制作 switch case?

javascript - If 语句不起作用 (Javascript)

c - 我如何重写这个 if-else 语句,使其不使用跳转?

swift - 在 While Loop Swift 中更新文本