How to calculate the center of a rectangle in C

1 Answer

0 votes
#include <stdio.h>

typedef struct {
    double x;
    double y;
} Point;

typedef struct {
    Point topLeft;
    Point bottomRight;
} Rectangle;

// Function to calculate the center point of a rectangle
Point getCenter(Rectangle rect) {
    Point center;

    // Compute the average of the x and y coordinates
    center.x = (rect.topLeft.x + rect.bottomRight.x) / 2.0;
    center.y = (rect.topLeft.y + rect.bottomRight.y) / 2.0;

    return center;
}

int main() {
    // Create a rectangle with top-left and bottom-right
    Rectangle rect = {{10.0, 20.0}, {110.0, 70.0}};

    // Compute the center of the rectangle
    Point center = getCenter(rect);

    printf("Center of the rectangle: (%.2f, %.2f)\n", center.x, center.y);

    return 0;
}


   
/*
run:
   
Center of the rectangle: (60.00, 45.00)
 
*/

 



answered Jun 22, 2025 by avibootz
edited Jun 22, 2025 by avibootz

Related questions

1 answer 74 views
1 answer 86 views
1 answer 106 views
1 answer 80 views
1 answer 93 views
2 answers 135 views
...