find the midpoint between two points in go

To find the midpoint between two points (x1, y1) and (x2, y2), we can use the following formula:

midpoint = ((x1 + x2) / 2, (y1 + y2) / 2)

In Go, we can create a function that takes in two points as arguments and returns the midpoint as a new point.

main.go
package main

import "fmt"

type point struct {
  x float64
  y float64
}

func midpoint(p1, p2 point) point {
  return point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2}
}

func main() {
  p1 := point{1.0, 2.0}
  p2 := point{3.0, 4.0}
  fmt.Println(midpoint(p1, p2)) // Output: {2 3}
}
280 chars
19 lines

In the above code, we define a point struct that represents a point in 2D space with an x and y coordinate. The midpoint function takes in two points p1 and p2, and returns the midpoint as a new point by applying the formula mentioned above. Finally, in the main function, we create two points p1 and p2 and find their midpoint by calling the midpoint function.

gistlibby LogSnag