Golang 程式建立類並計算圓的面積和周長
要計算圓的面積和周長,我們可以採取以下步驟 −
- 定義一個 struct,圓的屬性如 半徑。
- 定義一個計算圓面積的方法。
- 定義一個計算圓周長的方法。
- 在 main 方法中,接受使用者輸入的圓半徑。
- 使用 半徑例項化 圓。
- 列印圓的面積。
- 列印圓的周長。
例項
package main
import (
"fmt"
"math"
)
type Circle struct {
radius float64
}
func (r *Circle)Area() float64{
return math.Pi * r.radius * r.radius
}
func (r *Circle)Perimeter() float64{
return 2 * math.Pi * r.radius
}
func main(){
var radius float64
fmt.Printf("Enter radius of the circle: ")
fmt.Scanf("%f", &radius)
c := Circle{radius: radius}
fmt.Printf("Area of the circle is: %.2f\n", c.Area())
fmt.Printf("Perimeter of the circle is: %.2f\n", c.Perimeter())
}輸出
Enter radius of the circle: 7 Area of the circle is: 153.94 Perimeter of the circle is: 43.98
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP