-1
    // 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。你能纠正我做错的地方吗?请做必要的事情。

4

1 回答 1

0

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

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

因此,它恰好在 main 中打印 1 只是偶然的机会。但是无论它打印什么都是错误的,因为您似乎希望输出仅限于collatz.

您可以尝试玩电脑并用铅笔和纸执行您的功能。不会花很长时间。当然,您也可以使用调试器。

于 2016-05-28T23:58:02.487 回答