gpt4 book ai didi

c - 理解算法的一部分

转载 作者:行者123 更新时间:2023-11-30 20:50:23 25 4
gpt4 key购买 nike

下面是我在项目中使用的算法的一部分,但由于这是我第一次使用算法,我不明白以下几行。请需要您的帮助。

For i=1 to n do
t[i] .mark <-- 0
t[i] .num <-- -1
End

最佳答案

此伪代码可以翻译为C

使用结构

struct cm{
int mark;
int num;
};


#define N 10

int main(void)
{

struct cm t[N];

for (int i=0;i<N;i++){
t[i].mark = 0;
t[i].num = -1;
}

//print your struct elements field
for (int i=0;i<N;i++){
printf("%d: %d, %d\n",i ,t[i].mark, t[i].num);
}

}

我们有一个struct数组,因为我们需要它的每个元素都有两个数据字段(即mark,num)。

struct cm t[N]; 定义一个 N 长度的结构体 cm 数组。

在循环中,我们为数组元素的每个字段分配适当的值。

为了提高可读性,在这种情况下,您可以使用 typedef 而不是使用 struct 来定义所需的数据结构。 typedef vs struct

使用typedef

typedef struct typecm{
int mark;
int num;
}typecm;


#define N 10

int main(void)
{

typecm s[N];

for (int i=0;i<N;i++){
s[i].mark = 0;
s[i].num = -1;
}

//print values
for (int i=0;i<N;i++){
printf("%d: %d, %d\n",i ,s[i].mark, s[i].num);
}
}

关于c - 理解算法的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45827480/

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