Golang程序 创建一个类并计算圆的面积和周长

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())
}
Go

输出

Enter radius of the circle: 7
Area of the circle is: 153.94
Perimeter of the circle is: 43.98
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册