如何解决在结构数组中更改全局C变量
我有一种情况,我在一个单独的头文件中定义了一个全局结构数组,我希望能够从另一个文件中的函数进行更改,但我无法使其正常工作,我认为可以将问题简化为跟随者:
#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[2].x);
,
要获得所需的输出,请在printf
中替换main()
来自
printf("[0]: %d,coordinates[2].x);
收件人
printf("[0]: %.1f,[1]: %.1f,[2]: %.1f",coordinates[2].x);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。