Golang 如何找到圆的面积
在本教程中,我们将看到Golang程序来寻找一个圆的面积。面积是指任何封闭图形所覆盖的总空间。
公式
Area of Circle - 22 / 7 * r * r
r - radius of a Circle
例如,一个圆的半径是10厘米,所以圆的面积是-。
Area = 22 / 7 * 10 * 10
= 4.2857142857143
在函数中寻找圆的面积
算法
- 第1步 – 声明半径和面积的数据类型为float64的变量。
-
第2步 – 接受用户输入的半径值
-
第3步 – 在函数中使用上述公式求出面积
-
第4步 – 打印结果。
时间复杂度
O(1) – 时间复杂度是恒定的,因为无论输入什么,程序都会花费同样的时间。
空间复杂度
O(1) – 程序中的变量是静态的,所以空间复杂度也是恒定的。
例子1
在这个例子中,我们要在函数中找到一个圆的面积。
package main
// fmt package provides the function to print anything
import (
"fmt"
)
func main() {
// declaring the floating variables using the var keyword for
// storing the radius of the circle also a variable area to store Area
var radius, Area float64
fmt.Println("Program to find the Area of a Circle.")
// initializing the radius of a circle
radius = 5
// finding the Area of a Circle
Area = (22 / 7.0) * (radius * radius)
// printing the result
fmt.Println("Radius =", radius, "\nThe Area of the circule =", Area, "cm^2")
fmt.Println("(Finding the Area of a circle within the function)")
}
输出
Program to find the Area of a Circle.
Radius = 5
The Area of the circule = 78.57142857142857 cm^2
(Finding the Area of a circle within the function)
代码的描述
- var radius, Area float64 – 在这一行中,我们声明了我们以后要使用的半径和面积。由于半径或面积可以是小数,我们使用了浮点数据类型。
-
Area = (22 / 7.0) * (radius * radius) – 在这行代码中,我们正在应用公式并找到Area。
-
fmt.Println("Radius =", radius, "\nThe Area of the circule =", Area, "cm^2")– 打印圆的面积。
在单独的函数中求圆的面积
算法
-
第1步 – 声明半径和面积的数据类型为float64的变量
-
第2步 – 从用户那里获得半径的输入。
-
第3步 – 调用以半径为参数的函数,并存储函数返回的面积。
-
第4步 – 打印结果。
例子2
在这个例子中,我们将通过定义单独的函数来求出圆的面积。
package main
// fmt package provides the function to print anything
import (
"fmt"
)
func areaOfCircle(radius float64) float64 {
// returning the area by applying the formula
return (22 / 7.0) * (radius * radius)
}
func main() {
// declaring the floating variables using the var keyword for
// storing the radius of circle also a variable area to store Area
var radius, Area float64
fmt.Println("Program to find the Area of a Circle.")
// taking the radius of a Circle as input from the user
fmt.Print("Please enter the radius of a Circle:")
fmt.Scanln(&radius)
// finding the Area of a Circle using a separate function
Area = areaOfCircle(radius)
// printing the result
fmt.Println("The Area of a Circle whose radius is", radius, "is", Area, "cm^2.")
fmt.Println("(Finding the Area of a circle in the separate function)")
}
输出
Program to find the Area of a Circle.
Please enter the radius of a Circle:20
The Area of a Circle whose radius is 20 is 1257.142857142857 cm^2.
(Finding the Area of a circle in the separate function)
代码的描述
- var radius, Area float64 – 在这一行中,我们声明了我们以后要使用的半径和面积。由于半径或面积可以是十进制的,所以我们使用了float数据类型。
-
**fmt.Scanln( &radius) – **从用户那里获得半径的输入。
-
Area = areaOfCircle(radius) – 在这行代码中,我们正在调用寻找圆的面积的函数。
-
fmt.Println("The Area of a Circle whose radius is", radius, "is", Area, "cm^2.")- 打印圆的面积。
总结
以上是在Golang中查找圆的面积的两种方法。第二种方法在模块化和代码重用性方面要好得多,因为我们可以在项目的任何地方调用这个函数。
极客教程