在结构数组中更改全局 c 变量

Changing global c variable inside a struct array

我有一个案例,我在一个单独的头文件中定义了一个全局结构数组,我希望能够从另一个文件中的函数更改它,但我无法使其工作,我相信问题可能是简化为:

#include <stdio.h>

struct point{
    /*
    Measured points and reflector coordinates, both true and estimated
    are stored as points.
    */
    float x;    // x-coordinate [mm]
    float y;    // y-coordinate [mm]
} coordinates[3];


void set_value(){
    coordinates[0].x = 10.0;
    coordinates[1].x = 11.0;
    coordinates[2].x = 12.0;
}

int main(int argc, char const *argv[])
{
    set_value();
    printf("[0]: %d, [1]: %d, [2]: %d", coordinates[0].x, coordinates[1].x, coordinates[2].x);

}

这给出了以下无意义的输出:

[0]: 0, [1]: 1076101120, [2]: 0

我想要的输出如下:

[0]: 10.0, [1]: 11.0, [2]: 12.0

我做错了什么?


编辑: 只是我在测试不同的结构类型时忘记将 %d 更改为 %f

printf("[0]: %d, [1]: %d, [2]: %d", coordinates[0].x, coordinates[1].x, coordinates[2].x);

你为printf使用了错误的控制格式,它应该是%f而不是浮动变量:

printf("[0]: %f, [1]: %f, [2]: %f", coordinates[0].x, coordinates[1].x, coordinates[2].x);

要获得所需的输出,请将 printf 替换为 main()

来自

printf("[0]: %d, [1]: %d, [2]: %d", coordinates[0].x, coordinates[1].x, coordinates[2].x);

printf("[0]: %.1f, [1]: %.1f, [2]: %.1f", coordinates[0].x, coordinates[1].x, coordinates[2].x);