How to calculate the center of a rectangle in C#

1 Answer

0 votes
using System;

class RectangleCenter
{
    class Point {
        public double x, y;

        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }

    class Rectangle {
        public Point topLeft;
        public Point bottomRight;

        public Rectangle(Point topLeft, Point bottomRight) {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }
    }

    static Point GetCenter(Rectangle rect) {
        double centerX = (rect.topLeft.x + rect.bottomRight.x) / 2.0;
        double centerY = (rect.topLeft.y + rect.bottomRight.y) / 2.0;
        return new Point(centerX, centerY);
    }

    static void Main()
    {
        Rectangle rect = new Rectangle(
            new Point(10.0, 20.0),
            new Point(110.0, 70.0)
        );

        Point center = GetCenter(rect);
        Console.WriteLine("Center of the rectangle: ({0:F2}, {1:F2})", center.x, center.y);
    }
}


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

 



answered Jun 22, 2025 by avibootz

Related questions

1 answer 41 views
1 answer 89 views
1 answer 66 views
1 answer 83 views
2 answers 110 views
...