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
广告