gpt4 book ai didi

C 用循环初始化结构

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:46 24 4
gpt4 key购买 nike

下面是我正在编写的程序中结构的代码。我希望能够在某种循环中初始化这些参数,但我似乎无法弄清楚如何配置 .water/.air/.purge 属性以通过循环更新。 nozzle_count 是 16,所以我想找到一种方法来实现下面的代码,而不必只复制和粘贴它 16 次。我很感激任何意见。谢谢!

static nozzle nozzles[nozzle_count] = {
{
.water = C1_WATER, .air = C1_AIR, .purge = C1_PURGE,
.interval = 15*60*1000, .cycle = 0*3*5*1000, .purge_length = 0*4*1000,
.state = WAIT
},
{
.water = C2_WATER, .air = C2_AIR, .purge = C2_PURGE,
.interval = 2*60*1000, .cycle = 1*3*1000, .purge_length = 0*4*1000,
.state = WAIT
},
{
.water = C3_WATER, .air = C3_AIR, .purge = C3_PURGE,
.interval = 2*60*1000, .cycle = 0*1*5*1000, .purge_length = 0*4*1000,
.state = WAIT
}
{
.water = C4_WATER, .air = C4_AIR, .purge = C4_PURGE,
.interval = 2*60*1000, .cycle = 0*1*5*1000, .purge_length = 0*4*1000,
.state = WAIT
}
{
.water = C5_WATER, .air = C5_AIR, .purge = C5_PURGE,
.interval = 2*60*1000, .cycle = 0*1*5*1000, .purge_length = 0*4*1000,
.state = WAIT
}
};

最佳答案

我认为您的代码看起来非常好,即使您的数组长度从 5 增加到 16。两个可能的建议。

如果你去掉 C99 初始化的绒毛,那么一切都可以放在一行中:

static nozzle nozzles[nozzle_count] = {
// water air purge interval cycle purge_length state
// -------- ------ -------- ---------- ---------- ------------ ----
{ C1_WATER, C1_AIR, C1_PURGE, 15*60*1000, 0*3*5*1000, 0*4*1000, WAIT },
// ...
};

这是一个简单的表格,只有16行,清晰明了,易于维护。

其次,如果您需要保持每个成员的初始化,您可以将它包含在一个宏中,这有助于 DRY:

#define FOO(a, b, c, d, e, f, g)                                 \
{ \
.water = (a), .air = (b), .purge = (c), \
.interval = (d), .cycle = (e), .purge_length = (f), \
.state = (b) \
}

static nozzle nozzles[nozzle_count] = {
// water air purge interval cycle purge_length state
// -------- ------ -------- ---------- ---------- ------------ ----
FOO( C1_WATER, C1_AIR, C1_PURGE, 15*60*1000, 0*3*5*1000, 0*4*1000, WAIT ),
// ...
};

关于C 用循环初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51488245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com