How to calculate the center of a rectangle in Go

2 Answers

0 votes
package main

import (
    "fmt"
)

type Point struct {
    x, y float64
}

type Rectangle struct {
    topLeft, bottomRight Point
}

func getCenter(rect Rectangle) Point {
    centerX := (rect.topLeft.x + rect.bottomRight.x) / 2.0
    centerY := (rect.topLeft.y + rect.bottomRight.y) / 2.0
    return Point{centerX, centerY}
}

func main() {
    rect := Rectangle{
        topLeft:     Point{10.0, 20.0},
        bottomRight: Point{110.0, 70.0},
    }

    center := getCenter(rect)
    fmt.Printf("Center of the rectangle: (%.2f, %.2f)\n", center.x, center.y)
}



/*
run:

Center of the rectangle: (60.00, 45.00)

*/

 



answered Jun 23, 2025 by avibootz
0 votes
package main

import (
    "fmt"
    "image"
)

func getCenter(rect image.Rectangle) image.Point {
    centerX := (rect.Min.X + rect.Max.X) / 2
    centerY := (rect.Min.Y + rect.Max.Y) / 2
    
    return image.Pt(centerX, centerY)
}

func main() {
    // Define the rectangle with Min and Max points
    rect := image.Rect(10, 20, 110, 70)

    // Calculate the center
    center := getCenter(rect)

    fmt.Printf("Center of the rectangle: (%d, %d)\n", center.X, center.Y)
}



/*
run:

Center of the rectangle: (60, 45)

*/

 



answered Jun 23, 2025 by avibootz

Related questions

2 answers 103 views
1 answer 120 views
1 answer 124 views
1 answer 121 views
1 answer 89 views
1 answer 66 views
...