c - 编写一个函数来测试点是否在矩形中

标签 c arrays pointers struct floating-point

问题如下:

编写并测试具有以下功能的程序。

首先,定义一个名为 Point 的新结构类型,用 float 表示 x 和 y 值

。另外,定义一个名为 Rectangle 的新结构类型,它的边平行于 x 轴和 y 轴,允许您用 left_left 和 top_right 点表示矩形。

接下来编写一个函数,根据传递到函数中的 Rectangle 参数来计算并返回 Rectangle 的面积。

避免按值传递,确保函数表现出按引用传递行为

确保函数返回适当类型的数据

接下来编写一个函数来测试点是否在矩形中。该函数应通过引用接收两个参数,即要测试的 Point 和 Rectangle。如果该点位于矩形内部,则该函数必须返回整数值 1,否则应返回零。编写一个主函数,使用适当的局部变量作为测试数据,然后在上面的两个函数上使用

 #include <stdio.h>

 struct Point
 {
     float x;
     float y;
 };

 struct Rectangle
 {
     struct Point lb;    // left below point
     struct Point ru;    // right upper point
 };

 float getArea(struct Rectangle r)
 {
     return (r.ru.x - r.lb.x)*(r.ru.y - r.lb.y);
 }

 void setValue(struct Point* p, float x, float y)
 {
     p->x = x;
    p->y = y;
 }

 void setValueP(struct Rectangle* r, struct Point* lb, struct Point* ru)
 {
    r->lb = *lb;
     r->ru = *ru;
 }

 void setValueR(struct Rectangle* r, float x1, float y1, float x2, float y2)
 {
     r->lb.x = x1;
     r->lb.y = y1;
     r->ru.x = x2;
     r->ru.y = y2;
 }

 int contains(struct Rectangle r, struct Point p)
 {
     if((p.x > r.lb.x && p.x && p.x < r.ru.x) && (p.y > r.lb.y && p.y && p.y < r.ru.y))
        return 1;
     return 0;
 }

 int main()
 {
     struct Rectangle r;
    setValueR(&r, 1, 2, 6, 8);

     printf("%f\n", getArea(r));

     struct Point p1;
    setValue(&p1, 4, 5);
     struct Point p2;
     setValue(&p2, 4, 1);

     if(contains(r, p1))
         printf("inside the Rectangle\n");
     else
         printf("outside the Rectangle\n"); 

     if(contains(r, p2))
         printf("inside the Rectangle\n");
     else
         printf("outside the Rectangle\n"); 
 }

最佳答案

确保你编译了c++,这些错误看起来像用c编译器编译的c++代码

关于c - 编写一个函数来测试点是否在矩形中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015119/

相关文章:

c - 使用系统调用进行子字符串搜索

对象的 Javascript 计数数组

Typedef 中的 C++ 指针

c++ - 使用 OpenCV 复制指向的对象

c - C中的高精度除法

c - ls 如何对文件名进行排序?

C程序检查输入的字符是否为数字?

php - MYSQL:按数组的平均值排序

javascript - 用另一个 Javascript 数组对数组进行子集化

在某些情况下无法返回有意义值的 c++ 函数