gpt4 book ai didi

c - 确定矩形是否重叠,如果重叠则返回重叠矩形的面积与给定集合的比较

转载 作者:行者123 更新时间:2023-11-30 17:36:54 25 4
gpt4 key购买 nike

我是一名初学者程序员,正在为自己进行基本测试,以掌握使用 C 语言的核心值(value)。我有一个测试用例,但真的不知道从哪里开始构建它以使用 GCC 进行编译。我有一个基本理论和伪代码摘要,但主要需要一些帮助来推进。

我已经用谷歌搜索了这个问题的相关问题和排列,但无法弄清楚 C 的逻辑。

鉴于以下逻辑:

Using the C language, have the function OverlappingRectangles(strArr) read the strArr parameter being passed which will represent two rectangles on a Cartesian coordinate plane and will contain 8 coordinates with the first 4 making up rectangle 1 and the last 4 making up rectange 2. It will be in the following format: "(0,0),(2,2),(2,0),(0,2),(1,0),(1,2),(6,0),(6,2)." Your program should determine the area of the space where the two rectangles overlap, and then output the number of times this overlapping region can fit into the first rectangle. For the above example, the overlapping region makes up a rectangle of area 2, and the first rectangle (the first 4 coordinates) makes up a rectangle of area 4, so your program should output 2. The coordinates will all be integers. If there's no overlap between the two rectangles return 0.

我迷路了。

应该首先添加这个:

  1. 给定一个字符串(n1,n2,n3,n4,m1,m2,m3,m4)
  2. 将字符串拆分为 string1(n1,n2,n3,n4) string2(m1,m2,m3,m4)
  3. 如果 n1+n4 < m1 或 n2+n3 < m2 或 m1+m4 < n1 或 m2+m3 < m1
  4. 计算相交矩形的面积并除以第一个矩形的面积。
  5. 否则
  6. 打印 0

最佳答案

您有一个以下形式的字符串:

(x1,y1)(x2,y2)(x2,y1)(x1,y2)(x3,y3)(x4,y4)(x4,y3)(x3,y4)

定义2个矩形:

r1 = (x1,y1) to (x2,y2)
r2 = (x3,y3) to (x4,y4)

您需要首先:

  1. 定义矩形的表示(结构)
  2. 解析(读取)字符串以提取 x1-x4y1-y4 的数字 - - 看看例如sscanf 及其返回值

您可以创建一个辅助函数,例如:

const char *parse_rectangle(const char *str, rectangle *r);

将从 str 中读取一个矩形 r,格式为 (x1,y1)(x2,y2)(x2,y1)(x1,y2) )(x3,y3)(包括任何验证)并返回指向下一个字符的指针。

现在,您将有两个矩形。

然后您可以计算这些矩形的交集作为第三个矩形,例如:

int intersection(const rectangle *r1, const rectangle *r2, rectangle *result);

如果矩形相交,则返回 1;如果不相交,则返回 0,并用交集填充 result。如果您使用的是 C99,则可以使用 _Bool 代替。

现在,您需要一个函数来计算面积,例如:

int area(const rectangle *r);

您可以将其传递给相交的矩形和第一个矩形以获得两者的面积。

现在,您只需将第一个矩形区域除以相交的矩形区域并打印结果即可。

关于c - 确定矩形是否重叠,如果重叠则返回重叠矩形的面积与给定集合的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22546424/

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