Golang程序 创建一个类并计算圆的面积和周长
为了计算圆的面积和周长,我们可以采取以下步骤
- 定义一个具有圆属性的 结构 ,如 半径
- 定义一个方法来计算圆的面积。
- 定义一个方法来计算圆的周长。
- 在 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
极客教程