【问题标题】:Changing global c variable inside a struct array更改结构数组中的全局 c 变量
【发布时间】:2020-08-25 06:51:20
【问题描述】:

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

#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中使用%f而不是%d
  • 可能会要求您的编译器通过打开所有警告来警告您此类错误,并注意它们在将来会有所帮助。

标签: arrays c struct global-variables


【解决方案1】:
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);

【讨论】:

    【解决方案2】:

    要获得所需的输出,请将 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多