Golang 如何查找正方形的面积
在本教程中,我们将看到Golang程序来寻找一个广场的面积。面积是指任何封闭图形所覆盖的总空间。

公式
Area of Square - (length of a side) * (length of a side)
s - length of a side of a Square
例如,一个正方形的边长是10厘米,所以正方形的面积是-
Area = 10 * 10
= 100 cm^2
在函数中寻找一个正方形的面积
算法
第1步 - 声明边长和面积的数据类型为float64的变量。
第2步 --初始化变量。
第3步 – 在函数中使用上述公式查找面积。
第4步 – 打印结果。
Time Complexity:
O(1)
Space Complexity:
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 length of the side of the Square also a variable area
// to store Area
var lengthOfSide, Area float64
fmt.Println("Program to find the Area of a Square.")
// initializing the length of the side of a Square
lengthOfSide = 10
// finding the Area of a Square
Area = (lengthOfSide * lengthOfSide)
// printing the result
fmt.Println("The Area of a Square whose length of the side is", lengthOfSide, "is", Area, "cm * cm.")
fmt.Println("(Finding the Area of a Square within the function)")
}
输出
Program to find the Area of a Square.
The Area of a Square whose length of the side is 10 is 100 cm * cm.
(Finding the Area of a Square within the function)
代码的描述
- var lengthOfSide, Area float64 – 在这一行中,我们声明了一个边的长度和我们以后要使用的面积。由于边的长度或面积可以是十进制的,我们使用了float数据类型。
-
Area = (lengthOfSide * lengthOfSide)– 在这行代码中,我们正在应用公式并找到面积。 -
fmt.Println(“The Area of a Square whose length of the side is”, lengthOfSide, “is”, Area, “cm * cm.”)- 打印正方形的面积。
在单独的函数中寻找正方形的面积
算法
第1步 - 声明边长和面积的float64数据类型的变量。
第2步 --初始化变量。
第3步 – 以边长为参数调用函数,并存储函数返回的面积。
第4步 – 打印结果。
例2
在这个例子中,我们将通过定义单独的函数来求一个正方形的面积。
package main
// fmt package provides the function to print anything
import (
"fmt"
)
func areaOfSquare(lengthOfSide float64) float64 {
// returning the area by applying the formula
return (lengthOfSide * lengthOfSide)
}
func main() {
// declaring the floating variables using the var keyword for
// storing the length of the side of the Square also a variable area
// to store Area
var lengthOfSide, Area float64
fmt.Println("Program to find the Area of a Square.")
// initializing the length of the side of a Square
lengthOfSide = 10
// finding the Area of a Square by calling areaOfSquare() function
Area = areaOfSquare(lengthOfSide)
// printing the result
fmt.Println("The Area of a Square whose length of a side is", lengthOfSide, "is", Area, "cm * cm.")
fmt.Println("(Finding the Area of a Square in the separate function)")
}
输出
Program to find the Area of a Square.
The Area of a Square whose length of a side is 10 is 100 cm * cm.
(Finding the Area of a Square in the separate function)
代码的描述
- var lengthOfSide, Area float64 – 在这一行中,我们声明了一个边的长度和我们以后要使用的面积。由于边的长度或面积可以是十进制的,所以我们使用了浮点数的数据类型。
-
Area = areaOfSquare(lengthOfSide) – 在这行代码中,我们调用了查找正方形面积的函数。
-
fmt.Println("The Area of a Square whose length of a side is", lengthOfSide, "is", Area, "cm * cm.")打印正方形的面积。
总结
以上是在Golang中查找正方形面积的两种方法。第二种方法在模块化和代码重用性方面要好得多,因为我们可以在项目的任何地方调用这个函数。
极客教程