嵌入式软件笔试题目记录①-C语言编程
这是一道涉及到结构体和数组遍历的函数题目。
首先看一下题目:
已知有N个点,求由这N个点组成的多边形的外接矩形的四个顶点坐标。即完善如下函数。
typedef struct{
int32_t nX;
int32_t nY;
} stCoord; // 点坐标结构体
/*
* arrCoord: 已知点的坐标数组
* nCount: 点的数量
* arrRect: 保存外接矩形顶点坐标数组,长度为 4
*/
void GetCoordRect(stCoord* arrCoord, int32_t nCount, stCoord* arrRect) {
...
}
算法思路:
初始化外接矩形的四个顶点坐标为第一个点的坐标,假设其为左上角点和右下角点。
遍历剩下的点,更新外接矩形的四个顶点坐标。具体方法如下:
a. 如果当前点的 x 坐标小于外接矩形的左上角点的 x 坐标,更新左上角点的 x 坐标;
b. 如果当前点的 x 坐标大于外接矩形的右下角点的 x 坐标,更新右下角点的 x 坐标;
c. 如果当前点的 y 坐标小于外接矩形的左上角点的 y 坐标,更新左上角点的 y 坐标;
d. 如果当前点的 y 坐标大于外接矩形的右下角点的 y 坐标,更新右下角点的 y 坐标;
根据更新后的四个顶点坐标构造一个新的矩形,将其顶点坐标保存在 arrRect 数组中。
#include <cstdint>
typedef struct{
int32_t nX;
int32_t nY;
} stCoord_t; // 点坐标结构体
/*
* arrCoord: 已知点的坐标数组
* nCount: 点的数量
* arrRect: 保存外接矩形顶点坐标数组,长度为 4
*/
void GetCoordRect(stCoord_t* arrCoord, int32_t nCount, stCoord_t* arrRect)
{
// 初始化外接矩形顶点为第一个点的坐标
stCoord_t topLeft = arrCoord[0];
stCoord_t bottomRight = arrCoord[0];
// 遍历剩下的点,更新外接矩形的四个顶点坐标
for (int i = 1; i < nCount; i++)
{
if (arrCoord[i].nX < topLeft.nX)
{
topLeft.nX = arrCoord[i].nX;
}
if (arrCoord[i].nX > bottomRight.nX)
{
bottomRight.nX = arrCoord[i].nX;
}
if (arrCoord[i].nY > topLeft.nY)
{
topLeft.nY = arrCoord[i].nY;
}
if (arrCoord[i].nY < bottomRight.nY)
{
bottomRight.nY = arrCoord[i].nY;
}
}
// 构造新的矩形并保存顶点坐标到 arrRect 数组中
arrRect[0] = topLeft;
arrRect[1].nX = bottomRight.nX;
arrRect[1].nY = topLeft.nY;
arrRect[2] = bottomRight;
arrRect[3].nX = topLeft.nX;
arrRect[3].nY = bottomRight
}
一开始我的疑问就是,不太了解结构体数组,不知道原来函数形参中定义的
stCoord_t* arrCoord //这里利用指针传入数组地址
原来就可以读写
arrCoord[i].nX
了。