我的 void 函数 return 是一个值,而不是 return 到主函数。

My void function returns a value and does not return to the main function.

我正在编写一个程序,要求飞行员输入坐标。然后,稍后在其他函数中使用这些坐标,例如计算平面的距离和角度

这是我的主要功能:

    int main()
{
    plane_checker();
    double angle_finder(int x, int y);
    double distance_plane(int x, int y, int z);
    void ils_conditions();
}

我的 plane_checker() 函数是:

plane_checker()
{
    printf("Please enter your identification code:");
    scanf("%s", &plane_name[0]);

    if( (plane_name[0]== 'j') || (plane_name[0]== 'f') || (plane_name[0]== 'm') || (plane_name[0]== 'J') || (plane_name[0]== 'F') || (plane_name[0]== 'M'))
    {
        printf("Sorry, we are not authorized to support military air vehicles.");;
    }
    else
    {
        printf("Please enter your current coordinates in x y z form:");
        scanf("%d %d %d", &x, &y, &z);

        if(z < 0)
        {
            printf("Sorry. Invalid coordinates.");
        }

    }
    return;
}

用户输入坐标后,我希望程序return到主函数,继续其他函数。但是,当我 运行 程序时,我的函数 returns 输入的 z 值并结束程序。如此处所示:

Please enter your identification code:lmkng
Please enter your current coordinates in x y z form:1 2 2

Process returned 2 (0x2)   execution time : 12.063 s
Press any key to continue.

这可能是什么原因造成的?我逐字检查了我的程序,但找不到这背后的原因?我错过了什么?

非常感谢您!

打开警告 (-Wall) 它会告诉你 plane_checker 因为你没有在声明中指定它它有一个隐含的 int return值。

test.c:1:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
plane_checker()
^

您还会收到有关未声明变量的许多其他警告和错误:x、y、z 和 plane_name。全部修复。如果它们是全局变量,则它们不应该是。


"I expect the program to return to the main function and continue with the other functions."

那些不是函数调用,它们是函数的前向声明。函数调用类似于 angle_finder(x, y).

很抱歉,您的代码充满了错误。我建议您退后一步,阅读更多 material 关于 C 语言编程的内容。

如果你不想让你的函数return像这样定义它

void plane_checker()
{
    printf("Please enter your identification code:");
    scanf("%s", &plane_name[0]);

    if( (plane_name[0]== 'j') || (plane_name[0]== 'f') || (plane_name[0]== 'm') || (plane_name[0]== 'J') || (plane_name[0]== 'F') || (plane_name[0]== 'M'))
    {
        printf("Sorry, we are not authorized to support military air vehicles.");;
    }
    else
    {
        printf("Please enter your current coordinates in x y z form:");
        scanf("%d %d %d", &x, &y, &z);

        if(z < 0)
        {
            printf("Sorry. Invalid coordinates.");
        }

    }

}

但是您将无法在 plane_checker 函数之外操作插入的数据。您应该 return 从 plane_checker() 插入数据或使用指针。 https://www.tutorialspoint.com/cprogramming/c_pointers.htm