用 Go 語言計算頂點的絕對值和比例。


示例

Abs(x, y) => √(x)2+(y)2

Scale(f) => (x*f, y*f)

方法

  • 將頂點定義為一個結構體。

  • 使用一些x和值初始化頂點。

  • 定義一個方法來計算絕對值(x, y)

  • 定義一個方法來計算比例(x*f, y*f)

示例

 線上演示

package main
import (
   "fmt"
   "math"
)
type Vertex struct {
   X, Y float64
}
func Abs(v Vertex) float64{
   return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func Scale(v *Vertex, f float64) {
   v.X = v.X * f
   v.Y = v.Y * f
}
func main() {
   v := Vertex{3, 4}
   fmt.Println("Given vertex is: ", v)
   fmt.Println("Absolute value of given vertex is: ", Abs(v))
   f := 10.0
   fmt.Printf("After scaling by %0.1f new vertex is: ", f)
   Scale(&v, f)
   fmt.Println(v)
   fmt.Println("Absolute value of given vertex is: ", Abs(v))
}

輸出

Given vertex is: {3 4}
Absolute value of given vertex is: 5
After scaling by 10.0 new vertex is: {30 40}
Absolute value of given vertex is: 50

更新於: 2021 年 3 月 18 日

198 次瀏覽

開啟你的 職業生涯職業生涯

透過完成課程獲得認證

開始使用
廣告