如何在 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 - 在這一行中,我們聲明瞭稍後將要使用的半徑和麵積。由於半徑或面積可能是小數,因此我們使用了 float 資料型別。
Area = (22 / 7.0) * (radius * radius) - 在此程式碼行中,我們應用公式並找到面積。
fmt.Println("半徑為", radius, "的圓的面積為", Area, "cm * cm。")
- 列印圓的面積。
在單獨的函式中查詢圓的面積
演算法
步驟 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("半徑為", radius, "的圓的面積為", Area, "cm * cm。")
- 列印圓的面積。
結論
這是在 Golang 中查詢圓面積的兩種方法。就模組化和程式碼可重用性而言,第二種方法要好得多,因為我們可以在專案的任何位置呼叫該函式。要了解有關 go 的更多資訊,您可以瀏覽這些 教程。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP