gpt4 book ai didi

C 编程 : Using struct Accessing an array within an array during a for loop

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

我无法完成此函数,主要是在我进入 for 循环并尝试访问数组内的 x 和 y 坐标以计算两者之间的距离时。

有一个名为 locations_t 的结构涉及字段

x_loc 和 y_loc 以及我的位置数组看起来像

locations[0] = {{0, 0}};

所以程序看起来会返回以下输出,但这样做是为了找到 locations[i],即距起始值的 min_dist。

query_loc = 10, 7
locations[0] = {{10, 10}} //distance between the two is 3

query_loc = 10, 7
locations[1] = {{9, 7}} // distance between is 1

// nearest would return locations[1]

这是我的代码

int location_nearest (location_t query_loc, location_t locations[], int num_locations)
{
// (Task 5.1) If num_locations equal to or less than 0, return NULL.
if(num_locations <= 0)
{
return NULL;
}
// (Task 5.2) Declare and initialise a pointer to location_t called nearest.
// The initial value is the address of the first element in the array.
location_t *nearest = &locations[0];

// (Task 5.3) Declare and initialise an integer called min_dist.
// The initial value is the city block distance from the query to
// the first element of the array.
// Hint: use location_dist.
int min_dist = location_dist(query_loc, locations[0]);

// (Task 5.4) Set up a for loop to iterate over the array.
// Skip the first element of the array, because we already know
// the distance from the first element to the query.
for(int i = 1; i < num_locations; i++)
{
// (Task 5.4.1) Compute the city block distance from the query
// to the current element of the array. This is the current
// distance. Make sure you remember it somehow.
int dist = (query_loc.x_loc - locations[i][0]) + (query_loc.y_loc - locations[i][1]);
// (Task 5.4.2) If the current distance is less than min_dist:
if(dist < min_dist)
{
// (Task 5.4.3) Overwrite min_dist with the current distance.
// Overwrite nearest with the address of the current element of
// the array.
min_dist = dist;
nearest = &locations[i]
}
}

// (Task 5.5) Return nearest.
return nearest;
}

最佳答案

如果您像这样执行 locations[i][0],您会将 locations 变量视为二维数组,它不会访问结构的第一个成员。

为了访问您可以使用的结构成员,

dot(.) operator for non pointer variable or arrow(->) operator for pointer variable followed by member name.

如下所示。

  int dist = (query_loc.x_loc - locations[i].x_loc) + (query_loc.y_loc - locations[i].y_loc);

代替

int dist = (query_loc.x_loc - locations[i][0]) + (query_loc.y_loc - locations[i][1]);

关于C 编程 : Using struct Accessing an array within an array during a for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51947478/

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