How to calculate the center of a rectangle in C++

1 Answer

0 votes
#include <iostream> 
 
struct Point {
    double x, y;
};
 
struct Rectangle {
    Point topLeft;
    Point bottomRight;
};
 
Point getCenter(const Rectangle& rect) {
    Point center;
 
    // X coordinate of center is the average of the x coordinates
    center.x = (rect.topLeft.x + rect.bottomRight.x) / 2.0;
 
    // Y coordinate of center is the average of the y coordinates
    center.y = (rect.topLeft.y + rect.bottomRight.y) / 2.0;
 
    return center; 
}
 
int main() {
    // Create a rectangle with top-left corner 
    // and bottom-right corner 
    Rectangle rect = {{10.0, 20.0}, {110.0, 70.0}}; 
 
    Point center = getCenter(rect);
 
    std::cout << "Center of the rectangle: ("
              << center.x << ", " << center.y << ")" << std::endl;
}
 
 
/*
run:
 
Center of the rectangle: (60, 45)
 
*/

 



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

Related questions

1 answer 71 views
1 answer 106 views
1 answer 80 views
1 answer 93 views
2 answers 135 views
...